I have a question about C++'s memory order "Sequential Consistent".
Background: After tested the example(shown below) provided by cppreference, which is also served as Listing 5.4 in Anthony Williams's C++ Concurrency in Action). I found that the assert is still not fired after all memory_order_seq_cst are replaced with memory_order_relaxed, which is contradictory to cppreference's statement
Any other ordering may trigger the assert because it would be possible for the threads c and d to observe changes to the atomics x and y in opposite order.
and Anthony's statement:
This constraint doesn’t carry forward to threads that use atomic operations with relaxed memory orderings;
In other words, according to my test(10000+ times), or online test, there is no much difference between seq_cst and relaxed orders, that is, if I changed memory order from 'Sequential Consistent' to 'Relaxed', the program yields the same result.
So my question is:
Why the
Relaxedordering behaves as the same way as theSequential Consistentordering in this example?
Test:
# Compile
c++ example.cc
# Check 1000+ times
for i in {1..100000}; do ./a.out; done;
# ...... all succeed, none aborted
Code:
#include <thread>
#include <atomic>
#include <cassert>
std::atomic<bool> x = {false};
std::atomic<bool> y = {false};
std::atomic<int> z = {0};
void write_x()
{
x.store(true, std::memory_order_relaxed);
}
void write_y()
{
y.store(true, std::memory_order_relaxed);
}
void read_x_then_y()
{
while (!x.load(std::memory_order_relaxed))
;
if (y.load(std::memory_order_relaxed)) {
++z;
}
}
void read_y_then_x()
{
while (!y.load(std::memory_order_relaxed))
;
if (x.load(std::memory_order_relaxed)) {
++z;
}
}
int main()
{
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x);
a.join(); b.join(); c.join(); d.join();
assert(z.load() != 0); // will never happen
}