取消parallel_for最有效的方法是什么
What's the most efficient way to cancel a parallel_for
从parallel_fo中取出最有效的方法是什么?为了摆脱循环的标准,我们执行以下操作:
for(int i = 0; i < 100; i+)
{
bool bValue = DoSomething();
//Break if bValue is true
if(bValue)
break;
}
我做了一些研究,在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();
}
});
});
-抛出异常
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;
}
});
structured_task_group
选项是唯一一个实际合理的选项#3是非常不安全的,而#2只是对例外情况的可怕滥用。
从Visual Studio 2012开始,有一个run_with_cancellation_token
函数将执行lambda和cancellation_token
。lambda内部,
链接:run_with_cancellation_token函数
可以在MSDN上找到一个代码示例:How to:Use Cancellation to Break from A Parallel Loop
我不能说这种方法的"效率",因为我怀疑C++异常参与了它的实现。然而,此代码可能比其他方法更简单,并且它允许使用大多数PPL构造,而不限于structured_task_group
。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- 将此布尔值传递给此函数的最有效方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?