我正在阅读 CPP-Concurrency-In-Action-2ed-2019 这本书。在10.2.2章节中,作者给出了一个简单的例子:
std::vector<int> v(1000);
int count=0;
std::for_each(std::execution::seq,v.begin(),v.end(),
[&](int& x){ x=++count; });
但是与下面的代码片段有什么不同
std::for_each(v.begin(),v.end(),
[&](int& x){ x=++count; });
没有 std::execution::seq
的后者不是仍然按顺序存储计数吗?
std::execution::sequenced_policy 有什么用?
最佳答案
一种用途是为您的函数的用户提供并行运行它们的选项。以下是默认使用 sequenced_policy
的一个示例:
template <class ExecPolicy = std::execution::sequenced_policy>
void foo(std::vector<int>& vec, ExecPolicy pol = std::execution::seq) {
int count = 0;
std::for_each(pol, vec.begin(), vec.end(), [&](int& x) {
x = ++count;
});
}
注意:如果实际并行执行,++count
将会出现数据竞争。
但有一个区别:
std::execution::sequenced_policy
:
The invocations of element access functions in parallel algorithms invoked with this policy (usually specified as
std::execution::seq
) are indeterminately sequenced in the calling thread.
这意味着可以按任何顺序访问元素。
关于c++ - std::execution::sequenced_policy 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76873140/