QtConcurrent 命名空间提供了高级 API,使得能够在不使用低级线程原语(例如:互斥、读写锁、等待条件或信号量)的状况下编写多线程程序,使用 QtConcurrent 编写的程序根据可用的处理器核心数自动调整所使用的线程数。这意味着,当在将来部署多核系统时,如今编写的应用程序将继续适应。编程
在 C++ API changes 有关于 Qt Concurrent 的更改说明:安全
Qt Concurrent has been moved from Qt Core to its own modulemarkdown
意思是说,Qt Concurrent 已经被从 Qt Core 中移到本身的模块中了。因此,要连接到 Qt Concurrent 模块,须要在 qmake 项目文件中添加:多线程
QT += concurrent
注意: QtConcurrent::Exception 类被重命名为 QException,而且 QtConcurrent::UnhandledException 类被重命名为 QUnhandledException,他们仍然位于 Qt Core 中。 app
QtConcurrent 包含了函数式编程风格 APIs 用于并行列表处理,包括用于共享内存(非分布式)系统的 MapReduce 和 FilterReduce 实现,以及用于管理 GUI 应用程序异步计算的类:dom
Concurrent Map 和 Map-Reduce异步
Concurrent Filter 和 Filter-Reduce分布式
Concurrent Run函数式编程
QFuture:表示异步计算的结果函数
Qt Concurrent 支持多种兼容 STL 的容器和迭代器类型,可是最好使用具备随机访问迭代器的 Qt 容器,例如:QList 或 QVector。map 和 filter 函数都接受容器和 begin/end 迭代器。
STL 迭代器支持概述:
迭代器类型 | 示例类 | 支持状态 |
---|---|---|
Input Iterator | 不支持 | |
Output Iterator | 不支持 | |
Forward Iterator | std::slist | 支持 |
Bidirectional Iterator | QLinkedList, std::list | 支持 |
Random Access Iterator | QList, QVector, std::vector | 支持和推荐 |
在 Qt Concurrent 迭代大量轻量级 items 的状况下,随机访问迭代器能够更快,由于它们容许跳过容器中的任何点。此外,使用随机访问迭代器容许 Qt Concurrent 经过 QFuture::progressValue() 和 QFutureWatcher::progressValueChanged() 来提供进度信息。
非就地修改的函数(例如:mapped() 和 filtered()),在调用时会建立容器的副本。若是正在使用的是 STL 容器,此复制操做可能须要一段时间,在这种状况下,建议为容器指定 begin 和 end 迭代器。
厉害了 Concurrent,来看一个单词统计的示例:
#include <QList>
#include <QMap>
#include <QTextStream>
#include <QString>
#include <QStringList>
#include <QDir>
#include <QTime>
#include <QApplication>
#include <QDebug>
#include <qtconcurrentmap.h>
using namespace QtConcurrent;
// 递归搜索文件
QStringList findFiles(const QString &startDir, QStringList filters)
{
QStringList names;
QDir dir(startDir);
foreach (QString file, dir.entryList(filters, QDir::Files))
names += startDir + '/' + file;
foreach (QString subdir, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot))
names += findFiles(startDir + '/' + subdir, filters);
return names;
}
typedef QMap<QString, int> WordCount;
// 单线程单词计数器函数
WordCount singleThreadedWordCount(QStringList files)
{
WordCount wordCount;
foreach (QString file, files) {
QFile f(file);
f.open(QIODevice::ReadOnly);
QTextStream textStream(&f);
while (textStream.atEnd() == false)
foreach (const QString &word, textStream.readLine().split(' '))
wordCount[word] += 1;
}
return wordCount;
}
// countWords 计算单个文件的单词数,该函数由多个线程并行调用,而且必须是线程安全的。
WordCount countWords(const QString &file)
{
QFile f(file);
f.open(QIODevice::ReadOnly);
QTextStream textStream(&f);
WordCount wordCount;
while (textStream.atEnd() == false)
foreach (const QString &word, textStream.readLine().split(' '))
wordCount[word] += 1;
return wordCount;
}
// reduce 将 map 的结果添加到最终结果,该函数只能由一个线程一次调用。
void reduce(WordCount &result, const WordCount &w)
{
QMapIterator<QString, int> i(w);
while (i.hasNext()) {
i.next();
result[i.key()] += i.value();
}
}
int main(int argc, char** argv)
{
QApplication app(argc, argv);
qDebug() << "finding files...";
QStringList files = findFiles("../../", QStringList() << "*.cpp" << "*.h");
qDebug() << files.count() << "files";
int singleThreadTime = 0;
{
QTime time;
time.start();
// 单线程统计,与 mapreduce 机制实现的做对比
WordCount total = singleThreadedWordCount(files);
singleThreadTime = time.elapsed();
// 打印出所耗费的时间
qDebug() << "single thread" << singleThreadTime;
}
int mapReduceTime = 0;
{
QTime time;
time.start();
// mappedReduced 方式进行统计
WordCount total = mappedReduced(files, countWords, reduce);
mapReduceTime = time.elapsed();
qDebug() << "MapReduce" << mapReduceTime;
}
// 输出 mappedReduced 方式比单线程处理方式要快的倍数
qDebug() << "MapReduce speedup x" << ((double)singleThreadTime - (double)mapReduceTime) / (double)mapReduceTime + 1;
}
输出以下:
finding files…
2185 files
single thread 5221
MapReduce 2256
MapReduce speedup x 2.31427
能够看出,共查找了 2185 个文件,单线程使用了 5221 毫秒,MapReduce 方式使用了 2256 毫秒,比单线程要快 2.31427 倍。通过反复尝试,基本都在 2 倍以上。