c++中cppreference中一个多线程示例的解释

Interpretation of a multi-thread example from cppreference in C++

本文关键字:多线程 解释 一个 cppreference c++      更新时间:2023-10-16

我在cppreference中找到了一个程序:

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);
    while (x.load(std::memory_order_relaxed) == 1) { } // Error: assumes execution order
});

"错误:假定执行顺序"是什么意思,也就是说,这个程序的错误是什么?程序的目的似乎是显示死锁,但是我看不出来。

我知道标题不清楚,但我真的不知道如何描述这个问题,因为我在程序中找不到任何错误。不好意思

这个例子来自草案(例如N4606 [algorithms.parallel.exec]/3):

(例子:

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
});

上面的示例取决于迭代的执行顺序,如果两个迭代在同一执行线程上顺序执行,则不会终止。- end示例]