如何:使用取消來中斷平行迴圈

這個範例將示範如何使用取消來實作基本的平行搜尋演算法。

範例

下列範例會使用取消來搜尋陣列中的專案。 函 parallel_find_any 式會使用 concurrency::p arallel_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.
*/

並行 ::p arallel_for 演算法會同時作用。 因此,它不會以預先決定的循序執行作業。 如果陣列包含值的多個實例,則結果可以是其中一個位置。

編譯程式碼

複製範例程式碼,並將其貼到 Visual Studio 專案中,或貼到名為 parallel-array-search.cpp 的檔案中,然後在 Visual Studio 命令提示字元視窗中執行下列命令。

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

另請參閱

PPL 中的取消
平行演算法
parallel_for函式
cancellation_token_source 類別