- Volatile variable
In
computer programming , avariable or object declared with the volatile keyword may be modified externally from the declaring object. For example, a variable that might be concurrently modified by multiple threads may be declared volatile. Variables declared to be volatile will not be optimized by thecompiler because the compiler must assume that their values can change at any time. Note that operations on a volatile variable are still not guaranteed to be atomic.What can happen if volatile is not used?
The following pieces of C
source code demonstrate the use of thevolatile
keyword.static int
foo ; void bar(void) { foo = 0; while (foo != 255) continue; }In this example, the code sets the value stored in
foo
to 0. It then starts to poll that value repeatedly until it changes to 255. Anoptimizing compiler will notice that no other code can possibly change the value stored infoo
, and therefore assume that it will remain equal to 0 at all times. The compiler will then replace the function body with aninfinite loop , similar to this:void bar_optimized(void) { foo = 0; while (TRUE) continue; }
However,
foo
might represent a location that can be changed by other elements of the computer system. For example, the variable may be modified by another thread or process viashared memory . It could even be ahardware register of a device connected to theCPU . The value stored there could change at any time. The above code would never detect such a change; without thevolatile
keyword, the compiler assumes the current program is the only part of the system that could cause the value to change. (This is by far the most common situation.)To prevent the compiler from modifying code in this way, the
volatile
keyword is used in the following manner:static volatile int foo; void bar(void) { foo = 0; while (foo != 255) continue; }
With this modification the loop condition will not be optimized away, and the CPU will detect the change when it occurs.
For an example of the use of
volatile
in context, seeBusy waiting .External links
* [http://www.programmersheaven.com/articles/pathak/article1.htm Use of volatile at Programmer's Heaven]
* [http://msdn2.microsoft.com/en-us/library/12a04hfd.aspx volatile keyword in Visual C++]
* [http://kernel.org/doc/Documentation/volatile-considered-harmful.txt Why the "volatile" type class should not be used (Linux kernel documentation)]
* [http://softwareblogs.intel.com/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/ Volatile: Almost Useless for Multi-Threaded Programming (Intel Software Network)]
Wikimedia Foundation. 2010.