2 ms·
Actually I agree with the general point, OP is right that you should use volatile. I was just a bit taken back by the specific example above. However, as PeCaN
by reitzensteinm 7y ago
Actually I agree with the general point, OP is right that you should use volatile. I was just a bit taken back by the specific example above.
However, as PeCaN has pointed out, I'm probably suffering from tunnel vision from x86 monoculture.
- PeCaN 7y agoFor the record I think the specific example from the OP is rather silly and of course never an optimization on x86(_64), but I'd never pass up a chance to talk about more fun architectures ;-)
- lalaland1125 7y agoFor reference, volatile is still the wrong choice for thread safety. If you need your race condition semantics to be well defined, you must use atomics (do note that those atomics might compile down to simple assignments if the platform supports that, but only the compiler is allowed to do that).
- vnorilo 7y agoVolatile is, well, volatile. You can basically only rely on the fact that the compiler respects source order and keeps all reads and writes (instead of hoisting and reordering). I believe msvc used to put in memory barriers. Not sure if it still does. These days you are better off ignoring the entire keyword and using the properly specified atomic stuff.
- jcelerier 7y ago> I believe msvc used to put in memory barriers. Not sure if it still does. it does but now there's a flag to disable them : /volatile:iso (https://docs.microsoft.com/en-us/cpp/build/reference/volatile-volatile-keyword-interpretation?view=vs-2019 https://docs.microsoft.com/en-us/cpp/build/reference/volatil...).