本页内容

字数统计

演示如何使用 Map-Reduce 算法。

Qt Concurrent 的“词频统计”示例演示了将Map-Reduce算法应用于统计一组文件中词频的问题。

首先,应用程序启动一个 QFileDialog 以选择起始路径,然后将输出打印到控制台。

运行示例

您可以通过以下方式运行该示例:

比较操作方式

将文本文件中单词计数的单线程顺序方法与使用 mappedReduce() 的多线程方法进行比较:

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

mappedReduced 函数的第一个参数是要操作的容器。第二个参数是映射函数countWords() 。它由多个线程并行调用。第三个参数是归约函数reduce() 。对于映射函数返回的每个结果,该函数都会被调用一次,并生成最终的计算结果。

该函数返回一个类型为WordCount 的QFuture 对象。请立即对该QFuture 调用result 函数,以阻塞后续执行,直至结果可用。

注意:由于映射函数 会被多个线程调用,因此必须是线程安全的。

示例项目 @ code.qt.io

© 2026 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.