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
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。