I have the following scenario
// first assigned a value greater than 0
std::atomic<double> var=1;
//thread 1
while (True) {
var = 1;
}
//thread 2
if(var >0) {
//do something
}
My question is when thread 1
doing assignment, is there a possibility thread 2
sees var
other than 1? Possibly some random number or zero?
It seems to happen in my production build with O2
optimization(the above snippet is not the real code, O2 may optimize most away). It seems, according to the standard, that this should never happen.
Is my description correct, and the bug is elsewhere? Or am I missing something?
I am using c++17, gcc9.3.1
Yes, writes to atomic types are atomic. The bug in your code is elsewhere.
Because it has never been set to anything other than 1
, and the additional writes of 1
are atomic, there can't be any sort of "split read" where it reads some other value (as can happen on some architectures where the value may be written across multiple instructions, and a read might see the high bits but not the low bits).
This would be true even if the original number weren't 1
, as the reading thread will either see the entire write or not see the write at all (the definition of an atomic write).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments