如何最有效地退出parallel_for循环? 要退出标准的for循环,我们可以执行以下操作:
for(int i = 0; i < 100; i+)
{
bool bValue = DoSomething();
//Break if bValue is true
if(bValue)
break;
}
我做了一些研究,发现关于PPL中的取消操作有一些信息可供参考Cancellation in the PPL。我正在考虑三种选择:
-任务组
// 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;
}
});
parallel_for
是一个简单问题的简单工具:我有一堆沉重的任务要执行,并且我希望它们并行完成。parallel_for
负责处理所有细节。一旦您开始想要做一些parallel_for
明显不设计做的事情(比如中途停止),那么您显然需要比parallel_for
更强大的机制。 - Nicol Bolas