volatile keyword
table of Contents
1. Function
After a shared variable (class member variable, class static variable) is modified by volatile, there will be two layers of semantics
- The visibility of this variable to different threads is guaranteed, that is: after one thread modifies this value, another thread likes to be visible (note: atomicity is not guaranteed)
- Prohibit reordering of instructions (guarantee the orderliness of the row where the variable is located)
2. When to use
- Write operations to variables do not depend on the current value
- The variable is not included in an invariant with other variables,
such as: volatile int i, int j;