如何:使用取消中断 Parallel 循环

本示例说明如何使用取消操作来实现并行搜索算法。

示例

下面的示例使用取消操作来搜索数组中的元素。 parallel_find_any 函数使用 Concurrency::parallel_for 算法和 Concurrency::structured_task_group 对象搜索包含指定值的位置。 当工作函数找到该值时,它会调用 Concurrency::structured_task_group::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;

   // Use parallel_for to search for the element. 
   // The task group enables a work function to cancel the overall 
   // operation when it finds the result.

   structured_task_group tasks;
   tasks.run_and_wait([&]
   {
      parallel_for(std::size_t(0), count, [&](int n) {
         if (a[n] == what)
         {
            // Set the return value and cancel the remaining tasks. 
            position = n;            
            tasks.cancel();
         }
      });
   });

   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;
   }  
}

以下显示的是此示例的示例输出。

3123 is at position 4739.

Concurrency::parallel_for 算法并发作用。 因此,此算法不会按预先确定的顺序执行这些运算。 如果数组包含该值的多个实例,则结果可以是其任一位置。

编译代码

复制代码示例,再将此代码粘贴到 Visual Studio 项目中或一个名为 parallel-array-search.cpp 的文件中,然后在 Visual Studio 2010 命令提示符窗口中运行以下命令。

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

请参见

参考

parallel_for 函数

structured_task_group 类

概念

PPL 中的取消操作

并行算法