単語数

map-reduce アルゴリズムの使い方を示す。

Qt Concurrent Word Count のサンプルは、ファイルのコレクション内の単語を数える問題に適用したときの map-reduce アルゴリズムの使い方を示す。

まず、アプリケーションは QFileDialog を起動して開始パスを選択し、出力をコンソールに出力します。

例の実行

から例を実行するには Qt Creatorからサンプルを実行するには、Welcome モードを開き、Examples からサンプルを選択します。詳細については、Building and Running an Exampleを参照してください。

操作の比較

テキスト・ファイル内の単語をカウントするシングル・スレッドの逐次アプローチと、mappedReduced() を使用したマルチスレッド・アプローチを比較します:

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

mappedReduced 関数の最初の引数は、操作対象のコンテナである。第 2 引数はマッピング関数countWords() である。これは複数のスレッドから並列に呼び出される。3番目の引数は、リデューシング関数reduce() です。この関数は、マッピング関数が返す結果ごとに1回呼び出され、最終的な計算結果を生成する。

この関数は,WordCount 型のQFuture オブジェクトを返す.この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.