Typically, such a code indicates that vol_flag
is expected to be changed externally at some point. Here, the appearance may mean another thread, an interrupt handler, part of the hardware (in the case of displaying IO with memory), etc. This loop effectively expects an external event that changes the flag.
The volatile
keyword is a way for a programmer to express the fact that it is unsafe to assume what is obvious from the code: namely, that the flag does not change in the loop. Thus, this prevents the compiler from optimizing, which can compromise the intent of the code. Instead, the compiler is forced to reference memory to get the flag value.
Please note that (unlike Java) volatile
in C / C ++ does not establish a connection between events and does not guarantee any ordering or visibility of memory links in a tab. Moreover, it does not provide atomicity of variable links. Therefore, it is not a tool for communication between threads. See here for more details.
source share