c++11中引入了future/promise, 但是目前我使用的编译器并未完全支持c++11。查了一下,发现QT提供了future类。
使用QFuture( 阻塞)
#include <QCoreApplication>
#include <QtConcurrent/QtConcurrentRun>
#include <QDebug>
void print(const QString &name)
{
qDebug() << name;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFuture<void> future = QtConcurrent::run(print, QString("test"));
// 阻塞调用
future.waitForFinished();
}
使用QFuture( 非阻塞)
非阻塞调用,要配合QFutureWatcher, 把它和一个future相关联,他能在调用完成之后,发出QFutureWatcher::finished信号。 这样主线程就能去做其他事情,不用阻塞在等待future完成的那一步。
这里用一个读取图片的代码来举例子,因为读取图片可能耗时比较长,所以放到其他线程里面完成。
这是一个非常适合的使用future的场景。
class ImageReader : public QObject {
public:
QFuture<QImage> read(const QString& fileName);
};
QFuture<QImage> ImageReader::read(const QString &fileName)
{
auto readImageWorker = [](const QString &fileName) {
QImage image;
image.load(fileName);
return image;
};
return QtConcurrent::run(readImageWorker, fileName);
}
//....
// 使用代码
ImageReader reader;
QFuture future = reader.read(输入参数);
QFutureWatcher *watcher = new QFutureWatcher();
connect(watcher, &QFutureWatcher::finished,
[=]() {
setImage(future.result());
});
watcher->setFuture(future);
作者:Cosi_fan_tutte
链接:https://www.jianshu.com/p/1f5dff1d24ef
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。