| 1 |
// Copyright (C) 2023 The Qt Company Ltd. |
| 2 |
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only |
| 3 |
|
| 4 |
/*! |
| 5 |
\example wordcount |
| 6 |
\meta tags {threads, console} |
| 7 |
\title Word Count |
| 8 |
\ingroup qtconcurrentexamples |
| 9 |
\examplecategory {Data Processing & I/O} |
| 10 |
\brief Demonstrates how to use the map-reduce algorithm. |
| 11 |
|
| 12 |
The Qt Concurrent \e {Word Count} example demonstrates the use of the |
| 13 |
map-reduce algorithm when applied to the problem of counting words in a |
| 14 |
collection of files. |
| 15 |
|
| 16 |
First, the Application starts a QFileDialog to select a starting |
| 17 |
path, and then prints the output to the console. |
| 18 |
|
| 19 |
\include examples-run.qdocinc |
| 20 |
|
| 21 |
\section1 Comparing the operations |
| 22 |
|
| 23 |
Compare a single-threaded, sequential approach to counting the words in |
| 24 |
the text files to a multithreaded approach with mappedReduced(): |
| 25 |
|
| 26 |
\dots |
| 27 |
\snippet wordcount/main.cpp 1 |
| 28 |
\dots |
| 29 |
\snippet wordcount/main.cpp 2 |
| 30 |
\dots |
| 31 |
|
| 32 |
The first argument to the \l {QtConcurrent::}{mappedReduced} function is the |
| 33 |
container to operate on. The second argument is the mapping function |
| 34 |
\c {countWords()}. It is called in parallel by multiple threads. The |
| 35 |
third argument is the reducing function \c {reduce()}. It is called |
| 36 |
once for each result returned by the mapping function, and generates the |
| 37 |
final computation result. |
| 38 |
|
| 39 |
The function returns a QFuture object of type \c WordCount. Call the |
| 40 |
\l {QFuture::}{result} function immediately on this QFuture to block further |
| 41 |
execution until the result becomes available. |
| 42 |
|
| 43 |
\note The mapping function must be thread-safe since it is called from |
| 44 |
multiple threads. |
| 45 |
*/ |