Word Count

Demonstrates how to use the map-reduce algorithm.

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.

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, see Qt Creator: Tutorial: Build and run.

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.

The function returns a QFuture object of type WordCount. Call the result function immediately on this QFuture to block further execution until the result becomes available.

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

Example project @ code.qt.io

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.