QtConcurrent blockingMappedReduced v.s MappedReduced

时间:2016-11-08 05:24:45

标签: c++ qt qtconcurrent

根据我的理解QtConcurrent::blockingMappedReduced会返回最终结果,而QtConcurrent::MappedReduced会返回QFuture个对象,但在此示例中http://doc.qt.io/qt-5/qtconcurrent-wordcount-main-cpp.html我看到的代码如下:

WordCount total = QtConcurrent::mappedReduced(files, countWords, reduce);

QtConcurrent::mappedReduced函数也会返回最终结果。我错过了什么吗?如果这是错误的,那么使用QtConcurrent::mappedReduced返回的结果的正确方法是什么?在什么条件下我应该QtConcurrent::mappedReduced而不是QtConcurrent::blockingMappedReduced?请指教。

1 个答案:

答案 0 :(得分:3)

在示例QFuture中,使用QFuture对象conversion operator to its template parameter type将对象直接返回到WordCount,该对象阻止并等待结果可用。

typedef QMap<QString, int> WordCount;
WordCount total = mappedReduced(files, countWords, reduce);

实际上,如果您调用函数blockingMappedReduced的阻塞版本或从异步QFuture返回mappedReduced对象并立即阻止返回的QFuture对象,则它是相同的。请注意,调用result()resultAt(0)也会阻止。

WordCount total = blockingMappedReduced(files, countWords, reduce);

QFuture<WordCount> future = mappedReduced(files, countWords, reduce);
WordCount total = future.result();

如果您想与QFuture对象进行交互(暂停,恢复,检查结果是否准备好),那么您可以通过调用mappedReduced而不使用阻止函数来异步处理它。 / p>

QFuture<WordCount> future = mappedReduced(files, countWords, reduce);
qDebug() << future.isResultReadyAt(0); // returns false