英文:
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<int> v(1000);
int count=0;
std::for_each(std::execution::seq,v.begin(),v.end(),
[&](int& x){ x=++count; });
But what is the difference with the below snippet
std::for_each(v.begin(),v.end(),
[&](int& 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 <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;
});
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论