方法: キャンセル処理を使用して並列ループを中断する

取り消し処理を使用して、基本の並列検索アルゴリズムを実装する方法を示します。

次の例では、キャンセルを使用して配列内の要素を検索します。 この parallel_find_any 関数は、concurrency::parallel_for アルゴリズムと concurrency::run_with_cancellation_token 関数を使用して、指定された値を含む位置を検索します。 並列ループは、値を見つけると、、concurrency::cancellation_token_source::cancel メソッドを呼び出して、将来の作業を取り消します。

// parallel-array-search.cpp
// compile with: /EHsc
#include <ppl.h>
#include <iostream>
#include <random>

using namespace concurrency;
using namespace std;

// Returns the position in the provided array that contains the given value, 
// or -1 if the value is not in the array.
template<typename T>
int parallel_find_any(const T a[], size_t count, const T& what)
{
   // The position of the element in the array. 
   // The default value, -1, indicates that the element is not in the array.
   int position = -1;

   // Call parallel_for in the context of a cancellation token to search for the element.
   cancellation_token_source cts;
   run_with_cancellation_token([count, what, &a, &position, &cts]()
   {
      parallel_for(std::size_t(0), count, [what, &a, &position, &cts](int n) {
         if (a[n] == what)
         {
            // Set the return value and cancel the remaining tasks.
            position = n;
            cts.cancel();
         }
      });
   }, cts.get_token());

   return position;
}

int wmain()
{
   const size_t count = 10000;
   int values[count];
 
   // Fill the array with random values.
   mt19937 gen(34);
   for (size_t i = 0; i < count; ++i)
   {
      values[i] = gen()%10000;
   }
 
   // Search for any position in the array that contains value 3123.
   const int what = 3123;
   int position = parallel_find_any(values, count, what);
   if (position >= 0)
   {
      wcout << what << L" is at position " << position << L'.' << endl;
   }
   else
   {
      wcout << what << L" is not in the array." << endl;
   }
}
/* Sample output:
    3123 is at position 7835.
*/

concurrency::p arallel_for アルゴリズムは同時に動作します。 そのため、事前に決定された順序で操作は実行されません。 配列に値の複数のインスタンスが含まれている場合、結果はいずれかの任意の位置にできます。

コードのコンパイル

コード例をコピーし、Visual Studio プロジェクトに貼り付けるか、parallel-array-search.cpp という名前のファイルに貼り付けてから、Visual Studio のコマンド プロンプト ウィンドウで次のコマンドを実行します。

cl.exe /EHsc parallel-array-search.cpp

関連項目

PPL における取り消し処理
並列アルゴリズム
parallel_for関数
cancellation_token_source クラス