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

Gol*_*k84 5 c++ parallel-processing mfc for-loop

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

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

   //Break if bValue is true
   if(bValue)
      break;
}
Run Code Online (Sandbox Code Playgroud)

我做了一些研究,在 PPL 中 找到了一些有关取消的信息,我正在考虑 3 个选项

-任务组

// 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();
      }
   });
});
Run Code Online (Sandbox Code Playgroud)

-抛出异常

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

- 使用布尔值

// 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;
   }
});
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 3

structured_task_group选项是唯一真正合理的选项。#3 是非常不安全的,而 #2 则是对异常的可怕滥用。