volatile (computer programming)

In computer programming, a value is said to be volatile if it can be read or modified asynchronously by something other than the current thread of execution.

In particular, writing code with the volatile keyword for memory-mapped I/O devices is inherently non-portable and always requires deep knowledge of the specific target C/C++ implementation and platform.

Most C and C++ compilers, linkers, and runtimes simply do not provide the necessary memory ordering guarantees to make the volatile keyword useful for any multi-threading scenario.

Before the C11 and C++11 standards, programmers were forced to rely on guarantees from the individual implementations and platforms (e.g. POSIX and WIN32) to write multi-threading code.

The compiler will therefore replace the function body with an infinite loop similar to this: However, the programmer may make foo refer to another element of the computer system such as a hardware register of a device connected to the CPU which may change the value of foo while this code is running.

(This example does not include the details on how to make foo refer to a hardware register of a device connected to the CPU.)

The following C programs, and accompanying assembler language excerpts, demonstrate how the volatile keyword affects the compiler's output.

While intended by both C and C++, the current C standard fails to express that the volatile semantics refer to the lvalue, not the referenced object.

In C#, volatile ensures that code accessing the field is not subject to some thread-unsafe optimizations that may be performed by the compiler, the CLR, or by hardware.

Using the volatile keyword does not support fields that are passed by reference or captured local variables; in these cases, Thread.VolatileRead and Thread.VolatileWrite must be used instead.

The guarantees provided by Thread.VolatileRead and Thread.VolatileWrite are a superset of the guarantees provided by the volatile keyword: instead of generating a "half fence" (ie an acquire-fence only prevents instruction reordering and caching that comes before it), VolatileRead and VolatileWrite generate a "full fence" which prevent instruction reordering and caching of that field in both directions.