QtConcurrent 线程使用说明

关于Qt Concurrent,我们首先来看看Qt Assitant是怎么描述的。

The QtConcurrent namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives such as mutexes, read-write locks, wait conditions, or semaphores. Programs written with QtConcurrent automatically adjust the number of threads used according to the number of processor cores available. This means that applications written today will continue to scale when deployed on multi-core systems in the future.

说简单点,就是我们使用QtConcurrent 实现多线程时,可以不用考虑对共享数据的保护问题。而且,它可以根据CPU的能力,自动优化线程数。

QtConcurrent 主要提供了3种实现多线程的方法,分别是:run,map,filter。下面分别进行详细说明使用方法。

本文福利,费领取Qt开发学习资料包、技术视频,内容包括(Qt实战项目,C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

目录

  • Concurrent run,在线程池内起一个线程来执行一个函数。
  • Concurrent map, 用于并行处理一批数据的场景。
  • Concurrent Filter,顾名思义,一般用于对一批数据的过滤操作。

Concurrent run,在线程池内起一个线程来执行一个函数。基本用法如下:

extern void aFunction();
QFuture<void> future = QtConcurrent::run(aFunction);
//std::thread 实现
std::thread thread = std::thread(aFunction);
thread.detach();

如上,标准库的thread 也能实现相同功能。不同的是,QtConcurrent 实现的线程,可以获取到线程函数的返回值。

extern QString functionReturningAString();
QFuture<QString> future = QtConcurrent::run(functionReturningAString);
...
QString result = future.result();

QtConcurrent::run() 也提供了线程函数传参的实现:

extern QString someFunction(const QByteArray &input);
QByteArray bytearray = ...;
QFuture<QString> future = QtConcurrent::run(someFunction, bytearray);
...
QString result = future.result();

另外,同std::thread, QtConcurrent::run() 也提供了成员函数实现线程的方案。

1)调用const 函数

QByteArray bytearray = "hello world";
QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');

或,

QFuture<QList<QByteArray> > future = QtConcurrent::run(&bytearray, &QByteArray::split, ',');

2)调用非const 函数

QImage image = ...;
QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba);

Concurrent map, 用于并行处理一批数据的场景。主要包含map, mapped, mappedReduced 三种用法。

map 函数用于需要更改原数据的使用场景,使用方法如下:

void toUpper(QString &str)
{
    str = str.toUpper();
}
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::map(strWords, toUpper);
future.waitForFinished();
//strWords = {"APPLE", "BANANA", "COW", "DOG", "EGG"}

mapped 函数用于不改变原数据,返回处理结果的使用场景。使用方法如下:

QString toUpper(const QString &str)
{
    return str.toUpper();
}
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::mapped(strWords, toUpper);
future.waitForFinished();
qDebug() << future.results();
//输出:("APPLE", "BANANA", "COW", "DOG", "EGG")

mappedReduced 用于mapped处理后的结果还需要进行处理的使用场景。使用方法如下:

QString toUpper(const QString &str)
{
    return str.toUpper();
}
void reduceFun(QList<QString> &dictionary, const QString &string)
{
    dictionary.push_back(QString("result: ") + string);
}
 
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::mappedReduced(strWords, toUpper, reduceFun);
future.waitForFinished();
qDebug() << future.result();
//输出:("result: BANANA", "result: APPLE", "result: COW", "result: DOG", "result: EGG")

注意,上述代码输处结果的顺序与原数据的顺序已经不一样了。mappedReduced 函数的逻辑是,启动多个线程执行toUper 对链表中的每个元素进行处理,处理后的结果再逐一交给reduceFun函数处理。reduceFun 并不会等toUper的所有线程执行完毕后才开始执行,并且,同一时刻,只有一个reduceFun 线程在执行。如果需要使最后的输出结果顺序与输入相一致,就要用到mappedReduced 函数的第四个参数,赋值为QtConcurrent::OrderedReduce, 即可保证顺序一致。

同样的,Concurrent map也提供了成员函数作为线程函数的使用形式。线程函数必须是序列中元素的类型的成员函数。Qt 帮助文档中给出了如下示例:

// Squeeze all strings in a QStringList.
QStringList strings = ...;
QFuture<void> squeezedStrings = QtConcurrent::map(strings, &QString::squeeze);
 
// Swap the rgb values of all pixels on a list of images.
QList<QImage> images = ...;
QFuture<QImage> bgrImages = QtConcurrent::mapped(images, &QImage::rgbSwapped);
 
// Create a set of the lengths of all strings in a list.
QStringList strings = ...;
QFuture<QSet<int> > wordLengths = QtConcurrent::mappedReduced(strings, &QString::length, &QSet<int>::insert);

Concurrent map 还可以使用函数对象。Qt 帮助文档中给出了如下示例:

struct Scaled
{
    Scaled(int size): m_size(size) { }
    typedef QImage result_type;
 
    QImage operator()(const QImage &image)
    {
        return image.scaled(m_size, m_size);
    }
 
    int m_size;
};
 
QList<QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images, Scaled(100));

Concurrent Filter,顾名思义,一般用于对一批数据的过滤操作。同样也包含filter, filtered, filteredReduce 三种用法。

filter 函数必须按如下形式定义,T类型与处理数据的元素类型一致,返回false时,过滤掉相应的元素。

bool function(const T &t);

与Concurrent map 类似,filter 函数会改变原始数据,filtered 函数将处理结果保存在filtered 函数的返回值中,filteredReduce 会将过滤后的数据再调用reduceFun 函数处理。这里就不再进行详细赘述,可以完全参考map函数的用法使用。

本文福利,费领取Qt开发学习资料包、技术视频,内容包括(Qt实战项目,C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

猜你喜欢

转载自blog.csdn.net/m0_73443478/article/details/133133001
今日推荐