ascetic652 ascetic652 - 23 days ago 7
C++ Question

QtConcurrent blockingMappedReduced v.s MappedReduced

From my understanding

QtConcurrent::blockingMappedReduced
returns the final results, whereas
QtConcurrent::MappedReduced
returns a
QFuture
object, but in this example http://doc.qt.io/qt-5/qtconcurrent-wordcount-main-cpp.html I saw code like this:

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


QtConcurrent::mappedReduced
function also returns the final results. Am I missing something? If this is wrong, what is the correct way to use the results returned by
QtConcurrent::mappedReduced
? And under what condition I should
QtConcurrent::mappedReduced
instead of
QtConcurrent::blockingMappedReduced
? Please advise.

Answer

In the example QFuture object is returned directly to WordCount using QFuture object's conversion operator to its template parameter type which blocks and waits for the result to become available.

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

In practice, it's the same if you call blocking version of the function blockingMappedReduced or return QFuture object from asynchronous mappedReduced and block the returned QFuture object immediately. Note that calling result() or resultAt(0) also blocks.

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

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

If you want to interact with the QFuture object (pause, resume, check if results ready) then you can handle it asynchronously by calling mappedReduced and not using the blocking functions.

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