c++ - std::execution::sequenced_policy 有什么用?

标签 c++ c++17

我正在阅读 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/

相关文章:

c++ - 从模板化类版本控制派生类的序列化

c++ - 如何将节点添加到列表 vector ?

c++ - 为什么编译器不能推断出自动模板参数,除非我添加 const?

c++ - 为什么 2 不 > 0 ?它是 <= 0,但不是 < 0,也不 == 0

c++ - 基于std::any的属性系统:模板类型推导

C++ MinGW 如何从 Windows 为 Linx 进行编译

c++ - Select() 调用不工作本地主机

c++ - 构造函数内存泄漏引发异常

c++ - 我可以在 C++ 中扩展变体吗?

c++ - 我应该让我的局部变量是常量还是可 move ?