I heard that using if or switch on a std::atomic is a source of bugs, due to some arguments to do with memory ordering.
Specifically, code like:
std::atomic<bool> branchVar = false;
void secondThreadFunc() {
puts("Starting 2nd thread");
branchVar = true;
}
int main() {
std::thread t(secondThreadFunc);
Sleep(100);
// Branching on a std::atomic considered dangerous due to memory ordering issues?
if( branchVar ) {
puts("Branch true");
}
else {
puts("Branch false");
}
t.join();
}
Plants a race condition at the if(branchVar) call and is considered unsafe programming. A std::mutex should always be used to lock access of the branch variable instead
Is this true? Could someone explain to me why that is so? What about memory ordering would cause the std::atomic branch to cause a race condition?