xskxzr xskxzr - 3 months ago 16
C++ Question

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

I have found a program in 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
});


What does the word "Error: assumes execution order" mean, i.e. what is the error of this program? It seems that the program aims to show a deadlock, but I cannot see that.

I know the title is unclear, but I really don't know how to describe the problem since I cannot find any mistake in the program. Sorry about that.

Answer

This example is from the draft (e.g. N4606 [algorithms.parallel.exec]/3) :

[ Example:

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. — end example ]