To clarify:
volatile
is a C concept and tells the compiler to fetch a variable each time from memory rather then use a "compiler-generated" cached version in registers or optimise certain code.
What may be causing confusion here is CPU caches vs software caches (a.k.a variables in registers).
The CPU/Hardware cache is 100% transparent to the program and the hardware makes sure that it is 100% synchronised. There is nothing to worry there, when you issue a load
from memory and the data comes from the CPU cache then it's the same data that is in the addressed memory.
Your compiler may decide though to "cache" frequent use variables in registers which can then go out of sync with memory because the hardware is unaware of those. This is what the volatile
keyword prevents. Common example:
int * lock;
while (*lock) {
// do work
// lock mot modified or accessed here
}
An optimising compiler will see that you are not using lock
in the loop and will convert this to:
if (*lock)
while (true) {
// do work
}
This is obviously not the behaviour you want if lock
is to be modified by e.g. another thread. SO you mark it volatile to prevent this:
volatile int * lock;
while (*lock) {
// do work
}
Hope this makes it a little clearer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…