std::execution::sequenced_policy有什么用?

What is the use of std::execution::sequenced_policy?

提问人:f1msch 提问时间:8/10/2023 最后编辑:allejof1msch 更新时间:8/11/2023 访问量:89

问:

我正在阅读 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::sequenced_policy有什么用?std::execution::seq

C++ C++17

评论

0赞 Quimby 8/10/2023
您是否尝试过阅读 std::for_each 的文档?是的,两个调用是相等的。用例是您可以将执行作为参数传递。
0赞 Pepijn Kramer 8/10/2023
您可以在自己的模板类中使用 std::for_each,该模板类也具有策略并在内部使用 std::for_each。因此,用例是允许“组合”(在编译时)

答:

3赞 Ted Lyngmo 8/10/2023 #1

一种用法是为函数的用户提供并行运行函数的选项。下面是一个默认使用 :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::执行::sequenced_policy

使用此策略调用的并行算法中元素访问函数的调用(通常指定为 )在调用线程中不确定地排序std::execution::seq

这意味着可以按任何顺序访问这些元素。