The volatile
qualifier on a variable tells the compiler that whenever you access this variable, its value has to be loaded from memory, and that the compiler may assume nothing about this value from previous stores it has effected.
So it is appropriate whenever you have situations where a variable may have a value that can not be foreseen in the current "thread of execution" (in a broad sense). This includes:
- hardware registers
- status variables in signal handlers
- live variables that are used after
unexpected jumps such as
goto
,
switch
/case
, or, more important,
setjmp
/longjmp
.
volatile
is also necessary (but not sufficient!) for atomic access to thread shared variables to which the access is not mutexed. For that purpose volatile
is by no means sufficient to guarantee the atomic access, even if it is just for reading. For that, you'd have to use special instructions of the CPU that are not modeled (or interfaced) by the abstract machine of the current C standard, C99. The next standard, C1X, is supposed to have such primitives.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…