What happens during (! Volatile); do?

I saw this in a part that is never called in college code:

volatile unsigned char vol_flag = 0; // ... while(!vol_flag); 

vol_flag declared in the header file, but never changed. Will this lead to the fact that the program will hang in an infinite loop? Is there a way out of this?

+6
source share
1 answer

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.

+16
source

Source: https://habr.com/ru/post/915475/


All Articles