C++ 中 cppreference 中的 multi-thread 示例的解释
Interpretation of a multi-thread example from cppreference in C++
我在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
});
"Error: assumes execution order"这个词是什么意思,即这个程序的错误是什么?程序似乎是为了显示死锁,但我看不到。
我知道标题不清楚,但我实在不知道如何描述问题,因为我找不到程序中的任何错误。抱歉。
这个例子来自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 ]
我在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
});
"Error: assumes execution order"这个词是什么意思,即这个程序的错误是什么?程序似乎是为了显示死锁,但我看不到。
我知道标题不清楚,但我实在不知道如何描述问题,因为我找不到程序中的任何错误。抱歉。
这个例子来自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 ]