When learning 32 keywords in C language, we don't pay much attention to the volatile keyword. Volatile is a type modifier. Volatile is "changeable" in Chinese ". InProgramUnder what circumstances should we use him? We often see the use of this keyword when analyzing the kernel. Example:
Struct task_struct {volatile long state;/*-1 unrunnable, 0 runnable,> 0 stopped */void * stack; atomic_t usage; unsigned int flags;/* per process flags, defined below */unsigned int ptrace ;.......
In applications, volatile is mainly designed to modify variables accessed and modified by different threads.
The volatile variable indicates that this variable mayChanged unexpectedlyTherefore, the compiler should not be optimized accordingly. Precisely, the optimizer must carefully re-read the value of this variable every time when using this variable, rather than using the backup stored in the register.
For example:
Extern int A; // Statement 1 Suppose A is a global variable.
......
Int B = A; // Statement 2
Int c = A; // Statement 3
Statement 2 and 3 both use the value of A. When the optimizer references the value of A in Statement 3, it is assumed that the value of a has been read to the Register in statement 2, in addition, A is not modified between Statement 2 and Statement 3. Therefore, it is unnecessary to read the value of A in the memory. Therefore, the value in the register is used directly. However, if the interrupt occurs before Statement 3 is executed, the interrupt happens to modify. The value obtained from Statement 3 is incorrect.
If the above global variable A is modified to volatile, the optimizer cannot optimize Statement 3 and re-value it in the memory.
As an Embedded System Programmer, volatile must know how to use it.