字数统计

演示如何使用 map-reduce 算法。

Qt Concurrent 字数统计示例演示了如何使用 map-reduce 算法来计算文件集合中的字数。

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

运行示例

要运行来自 Qt Creator,打开Welcome 模式,并从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建和运行

比较操作

比较使用单线程顺序计算文本文件字数的方法和使用 mappedReduced() 的多线程方法:

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

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

该函数返回一个QFuture 类型的WordCount 对象。在此QFuture 上立即调用result 函数,以阻止进一步执行,直到结果可用。

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

示例项目 @ code.qt.io

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