- Qt 6.9
- Qt Concurrent
- Qt Concurrent Examples
- Word Count
- Qt 6.9.3 Reference Documentation

# 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