gpt4 book ai didi

c++ - C++ 标准中错误使用 std::memory_order::relaxed 的示例 [n4713 中的 algorithms.parallel.exec/5]

转载 作者:行者123 更新时间:2023-12-01 19:55:32 25 4
gpt4 key购买 nike

C++ 标准中滥用 std::memory_order::relaxed 的示例之一:

std::atomic<int> x{0};
int a[] = {1,2};
std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int) {
x.fetch_add(1, std::memory_order::relaxed);
// spin wait for another iteration to change the value of x
while (x.load(std::memory_order::relaxed) == 1) { } // incorrect: assumes execution order
});

然后它说,

The above example depends on the order of execution of the iterations, and will not terminate if both iterations are executed sequentially on the same thread of execution.

问题:

  1. 评论说:“不正确:假定执行顺序”。什么是“假定执行顺序”?我很想念它。

  2. “上面的示例取决于迭代的执行顺序”中的“迭代”指的是什么?这是否意味着while循环中的迭代?或者它指的是std::for_each 的迭代?

  3. 如果 std::for_each 的迭代由不同的线程并行执行,那么其中一个迭代/线程是否不会退出?因为 x.fetch_add(1, std::memory_order::relaxed) 是原子的,所以一个线程将使 x 1,另一个线程将使 x > 2 并且两个线程都不可能有 x == 1。没有?

最佳答案

"incorrect: assumes execution order". What's the "assumed execution order"?

它假设 lambda 的主体由多个线程而不是一个线程执行。该标准更确切地说它可以并行执行。

What does the "iterations" refer to in "The above example depends on the order of execution of the iterations"?

它可能指的是另一个线程执行 lambda。但该标准并不保证存在另一个线程。请参阅execution_policy_tag_t :

parallel_policy The execution policy type used as a unique type to disambiguate parallel algorithm overloading and indicate that a parallel algorithm's execution may be parallelized. The invocations of element access functions in parallel algorithms invoked with this policy (usually specified as std::execution::par) are permitted to execute in either the invoking thread or in a thread implicitly created by the library to support parallel algorithm execution. Any such invocations executing in the same thread are indeterminately sequenced with respect to each other.

关于c++ - C++ 标准中错误使用 std::memory_order::relaxed 的示例 [n4713 中的 algorithms.parallel.exec/5],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58287969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com