什么是取消parallel_for的最有效方法

时间:2012-09-10 18:32:31

标签: c++ mfc for-loop parallel-processing

离开parallel_for最有效的方法是什么? 为了摆脱循环标准,我们执行以下操作:

for(int i = 0; i < 100; i+)
{
    bool bValue = DoSomething();

   //Break if bValue is true
   if(bValue)
      break;
}

我做了一些研究,我在Cancellation in the PPL 找到了一些信息,我正在考虑3个选项

-Task Group

// To enable cancelation, call parallel_for in a task group.
structured_task_group tg;

task_group_status status = tg.run_and_wait([&] 
{
   parallel_for(0, 100, [&](int i) 
   {

      bool bValue = DoSomething();
      if (bValue)
      {
         tg.cancel();
      }
   });
});

- 抛出异常

try
{
   parallel_for(0, 100, [&](int i) 
   {
      bool bValue = DoSomething();
      if (bValue)
          throw i;
   });
}
catch (int n)
{
   wcout << L"Caught " << n << endl;
}

- 使用布尔值

// Create a Boolean flag to coordinate cancelation.
bool bCanceled = false;

parallel_for(0, 100, [&](int i) 
{       
   // Perform work if the task is not canceled.
   if (!bCanceled)
   {
       bool bValue = DoSomething();
       if (bValue)
          bCanceled = true;
   }
});

2 个答案:

答案 0 :(得分:2)

structured_task_group选项是唯一真正合理的选项。 #3简直是非常不安全,而#2只是一种可怕的例外滥用。

答案 1 :(得分:1)

从Visual Studio 2012开始,有一个run_with_cancellation_token函数将执行lambda和cancellation_token。在lambda里面,

链接:run_with_cancellation_token Function

可以在MSDN上找到代码示例:How to: Use Cancellation to Break from a Parallel Loop

我不能说这种方法的“效率”,因为我怀疑C ++异常涉及它的实现。但是,此代码可能比其他方法更简单,并且允许使用大多数PPL构造而不限于structured_task_group