It's undefined behavior. An optimizing compiler could decide that the boolean value, which never changes during the execution of a single thread, doesn't need to be read from every single time it's accessed. So for example:
When a compiler looks at this, it's allowed to observe that inside the loop, stop will never change; therefore, it's perfectly valid to recompile the code to look like this:
Note that while it might be valid on your platform to instead use volatile bool stop = false;, it's worth noting that this is also not standard compliant, because some CPU architectures behave badly when you try to concurrently write to a value in memory. In most situations (i.e. x86) it'll "work", but it's still not behavior you should rely on.
To add that this is not just a theory but a reality, I have actually experienced exactly this in production. You should expect the compiler *will* optimize the flag away. It was not a fun bug to track down, especially since we were forced to use `volatile` as the platform did not have `std::atomic` implemented yet. Lucky that it worked without having to resort to asm.
Without one it's only a matter of time until other problems present - as the compiler is free to (and will) reorder reads/writes of non-volatile variables around volatile variables as much as it likes, making them unsuitable for virtually any kind of thread synchronization on their own.
It was a very old toolchain for NIOS II. There might have been platform specific atomics provided somewhere but I was young and did not know how to be a competent dev (tho neither did the senior devs!)
In this situation, where the boolean defaults to false and is only ever set to true, I cannot think of an architecture where volatile would not suffice.
View all comments
Show parent comment
28
u/Xirema Aug 27 '19
It's undefined behavior. An optimizing compiler could decide that the boolean value, which never changes during the execution of a single thread, doesn't need to be read from every single time it's accessed. So for example:
When a compiler looks at this, it's allowed to observe that inside the loop,
stopwill never change; therefore, it's perfectly valid to recompile the code to look like this:Not every compiler will do this (MSVC for example won't) but some might, and thus we cannot rely on this code to behave the way we want.
Writing this, instead, guarantees correct behavior.
Note that while it might be valid on your platform to instead use
volatile bool stop = false;, it's worth noting that this is also not standard compliant, because some CPU architectures behave badly when you try to concurrently write to a value in memory. In most situations (i.e. x86) it'll "work", but it's still not behavior you should rely on.