Multithreaded programming (eight) volatile keyword

volatile keyword

1. Function

After a shared variable (class member variable, class static variable) is modified by volatile, there will be two layers of semantics

  1. 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)
  2. Prohibit reordering of instructions (guarantee the orderliness of the row where the variable is located)

2. When to use

  1. Write operations to variables do not depend on the current value
  2. The variable is not included in an invariant with other variables,
    such as: volatile int i, int j;

Guess you like

Origin blog.csdn.net/jinian2016/article/details/109703844