I was looking up the keyword volatile
and what it\'s for, and the answer I got was pretty much:
It\'s used to prevent the compiler from o
Condition variables are not where volatile
is needed; strictly it is only needed in device drivers.
volatile
guarantees that reads and writes to the object are not optimized away, or reordered with respect to another volatile
. If you are busy-looping on a variable modified by another thread, it should be declared volatile
. However, you shouldn't busy-loop. Because the language wasn't really designed for multithreading, this isn't very well supported. For example, the compiler may move a write to a non-volatile variable from after to before the loop, violating the lock. (For indefinite spinloops, this might only happen under C++0x.)
When you call a thread-library function, it acts as a memory fence, and the compiler will assume that any and all values have changed — essentially everything is volatile. This is either specified or tacitly implemented by any threading library to keep the wheels turning smoothly.
C++0x might not have this shortcoming, as it introduces formal multithreading semantics. I'm not really familiar with the changes, but for the sake of backward compatibility, it doesn't require to declare anything volatile that wasn't before.
Volatile doesn't try to keep data to a cpu register (100's of times faster than memory). It has to read it from memory every time it is used.