In general, volatile is used in the following places: 1, the interrupt Service program modified for other programs to detect variables need to add volatile;2, multi-tasking environment to share the flag should be added volatile;3, The hardware register of the memory map is usually also marked with a volatile description, because each time it is read and write may have different meanings, in addition, these situations often need to consider the integrity of the data (the correlation of several flags read half interrupted rewrite), in 1 can be achieved by the shutdown interrupt, 2 Can prohibit task scheduling, 3 can only rely on the good hardware design. A typical example
| 1 |
for(inti=0; i<100000; i++); |
This statement is used to test the speed of an empty loop, but the compiler is definitely going to optimize it and not execute it if you write
| 1 |
for(volatileinti=0; i<100000; i++); |
It executes a volatile variable that may change in situations where your program itself does not know, such as multi-threaded programs, shared memory, multiple programs can manipulate the variable your own program, is unable to determine when the variable will change, for example, He corresponds to a state of an external device, and when an external device is operating, through the driver and interrupt events, the system changes the value of the variable, and your program does not know it.for volatile types of variables, the system will be used every time he is extracted from the corresponding memory, instead of using the original cache value, to adapt to its unknown when the changes will occur, the system does not optimize the processing of this variable-- It is also obvious that it is possible to change the value at any time.
C Language---Volatile (my engineering Notebook)