std::execution::sequenced_policy 的用途是什么?

huangapple go评论101阅读模式
英文:

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

问题

我正在阅读《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 的用途是什么?

英文:

I am reading the book of CPP-Concurrency-In-Action-2ed-2019. In chapter 10.2.2, the author gives a simple example:

std::vector&lt;int&gt; v(1000);
int count=0;
std::for_each(std::execution::seq,v.begin(),v.end(),
  [&amp;](int&amp; x){ x=++count; });

But what is the difference with the below snippet

std::for_each(v.begin(),v.end(),
  [&amp;](int&amp; x){ x=++count; });

Is not the latter without std::execution::seq still store counts in sequence?
What is the use of std::execution::sequenced_policy?

答案1

得分: 3

一个用途可以是为您的函数的用户提供在并行运行它们的选项。以下是一个示例,其中默认值是使用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

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

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

英文:

One usage could be to supply users of your functions with the option to run them in parallel. Here's one example where the default is using the sequenced_policy:

template &lt;class ExecPolicy = std::execution::sequenced_policy&gt;
void foo(std::vector&lt;int&gt;&amp; vec, ExecPolicy pol = std::execution::seq) {
    int count = 0;
    std::for_each(pol, vec.begin(), vec.end(), [&amp;](int&amp; x) {
        x = ++count; 
    });
}

Note: ++count would have a data race if actually executed in parallel.

There's one difference though:

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.

This means that the elements could be accessed in any order.

huangapple
  • 本文由 发表于 2023年8月10日 14:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定