While watching this talk about the implementation of C++11 atomics in LLVM there was this piece of code
-- Initially --
int x = 0;
std::atomic<bool> flag1{false}, flag2{false};
-- Thread 1 --
x = 42;
flag1.store(true, std::memory_order_release);
while(!flag2.load(std::memory_order_acquire));
x = 43;
-- Thread 2 --
while(!flag1.load(std::memory_order_acquire));
printf("%d", x);
flag2.store(true, std::memory_order_release);
I consider this code data-race free (as is also stated by the speaker): it will never print anything but 42
.
However, I am not sure that it will ever print 42
. My question is: Wouldn't a compiler be allowed to reorder the store past the while-loop in Thread 1 so that both threads would deadlock? Or what part of the C++11 standard prevents such kind of behavior?