volatile is a keyword in C/C++ and Java, indicating a variable which is subject to rapid change and whose value should not be cached - a compiler or runtime environment will generally not, for instance, store a volitile variable in CPU registers, instead always reading from RAM, nor would it be used in speculative, out-of-order computations (because the value may have changed externally). The VolatileQualifier is useful in several contexts:
- In multithreaded programming, when you need to share a variable between threads. In general, more robust mechanisms (semaphores, monitors, etc.) should be used; but if it is just an int (or something else that the CPU can read/write atomically), and there is no need for atomic read/modify/writes, volatile will ensure the compiler keeps a fresh value around. To be used with extreme caution - or not at all - when as substitute for proper synchronization.
- During I/O, where out-of-order reads/writes, suppressed writes, and speculative reads cause incorrect behavior. Note that volatile is necessary but not sufficient; you probably will need to emit inline assembly to prevent inappropriate behavior on the part of the CPU pipeline and/or data cache. [My favorite such instruction is the PowerPc EIEIO instruction, Enforce In-order Execution of I/O. Who said that folks at IbmCorporation have no sense of humor? --ScottJohnson]
- When using setjmp()/longjmp(), the VolatileQualifier will make sure that critical variables needed by the setjmp handler are not clobbered.
- When working with hardware registers, the hardware itself will be changing the values in the register. It is kind of pointless to loop on a bit, waiting for it to be set, if the compiler is using a cached value in an internal CPU register.
Contributers: ScottJohnson