I would like to add that volatile is also very useful when working with multi-threaded applications, i.e. you have a main thread (where main () lives), and you create a work thread that will continue to rotate, and the variable "app_running" is true. main () determines whether app_running is true or false, so if you do not add a mutable attribute to the app_running declaration, if the compiler optimizes access to app_running in the code launched by the secondary thread, main () can change app_running "to false, but the secondary stream will continue to work because the value is cached. I saw the same behavior using gcc for Linux and VisualC ++. The volatile attribute placed in the app_running declaration solved the problem. Thus, this is a scenario in which no hardware interrupts or kernel are used when changing the values โโof such variables.
BinCoder 30 Oct. '13 at 18:04 on 2013-10-30 18:04
source share