gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:24 25 4
gpt4 key购买 nike

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

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

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

我做了一些研究,发现了一些关于 Cancellation in the 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;
}

-使用 bool 值

// 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 只是对异常的可怕滥用。

关于c++ - 取消 parallel_for 的最有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12357490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com