Word Count

演示如何使用 map-reduce (映射缩减) 算法。

The Qt Concurrent Word Count example demonstrates the use of the map-reduce algorithm when applied to the problem of counting words in a collection of files.

First, the Application starts a QFileDialog to select a starting path, and then prints the output to the console.

运行范例

要运行范例从 Qt Creator ,打开 Welcome 模式,然后选择范例从 Examples 。更多信息,拜访 构建和运行范例 .

Comparing the operations

Compare a single-threaded, sequential approach to counting the words in the text files to a multithreaded approach with mappedReduced():

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

The first argument to the mappedReduced function is the container to operate on. The second argument is the mapping function countWords() . It is called in parallel by multiple threads. The third argument is the reducing function reduce() . It is called once for each result returned by the mapping function, and generates the final computation result.

函数返回 QFuture object of type WordCount . Call the result function immediately on this QFuture to block further execution until the result becomes available.

注意: The mapping function must be thread-safe since it is called from multiple threads.

范例工程 @ code.qt.io