Case
Case1:
According to the gcc documentation the following assertion will not fail
https://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync
-Thread 1-
x.store (1, memory_order_relaxed)
x.store (2, memory_order_relaxed)
-Thread 2-
y = x.load (memory_order_relaxed)
z = x.load (memory_order_relaxed)
assert (y <= z)
The assert cannot fail. Once the store of 2 is seen by thread 2, it can no longer see the value 1. This prevents coalescing relaxed loads of one variable across relaxed loads of a different reference that might alias. There is also the presumption that relaxed stores from one thread are seen by relaxed loads in another thread within a reasonable amount of time. That means that on non-cache-coherent architectures, relaxed operations need to flush the cache (although these flushes can be merged across several relaxed operations) The relaxed mode is most commonly used when the programmer simply wants an variable to be atomic in nature rather than using it to synchronize threads for other shared memory data.
Case2:
In the same way, case2 assertion will not fail, right?
std::atomic<bool> x{false}, y{false};
void thread1() {
x.store(true, std::memory_order_relaxed); // (1)
y.store(true, std::memory_order_relaxed); // (2)
}
void thread2() {
while (!y.load(std::memory_order_relaxed)); // (3)
assert(x.load()); // (4)
}
test
#include <atomic>
#include <thread>
#include <cassert>
std::atomic<bool> x{false}, y{false};
void thread1() {
x.store(true, std::memory_order_relaxed); // (1)
y.store(true, std::memory_order_relaxed); // (2)
}
void thread2() {
while (!y.load(std::memory_order_relaxed)); // (3)
assert(x.load()); // (4)
}
void fn() {
int i;
while(i < 10000000) {
x.store(false, std::memory_order_relaxed);
y.store(false, std::memory_order_relaxed);
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
i++;
}
}
int main() {
fn();
return 0;
}
So memory_order_relaxed is safety?
xing franics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.