Definition
The volatile qualifier is a C and C++ keyword that marks an object, a region of storage holding a value, as one that may change, or whose access may have effects, in ways the compiler cannot see. The compiled program must then perform every read and write of the object that the source performs, as many times as written and in source order relative to other volatile accesses. Hardware device registers are the main use. Volatile provides no indivisibility, mutual exclusion or ordering between threads.
The idea
A compiler improves a program by removing work whose outcome it can predict; this is compiler optimization §3.39. Take a loop that waits for a hardware status bit:
while ((*status & 1) == 0) { }
Here status points at a device register, a storage location inside a peripheral device that the processor reads at a memory address. Nothing in the loop writes *status, so the compiler may conclude that the value cannot change, read it once, and turn the loop into either no wait at all or a wait that never ends. The register does change, but a device changes it, and the compiler cannot see the device.
Declaring the pointer as volatile uint32_t *status tells the compiler that every read of *status is an event in its own right that must happen. The compiled loop then reads the register on every pass. A picture helps: an ordinary variable is a note the compiler may copy once and consult later, while a volatile object is a window that must be looked through every time. The picture stops at one point. Looking through one window every time says nothing about what other people at other windows see, or when. Volatile governs how the compiler treats accesses to one object; it says nothing about how two threads coordinate.
How it works
An optimizing compiler may do four things to accesses of an ordinary object that it may not do to a volatile one.
Keep the value in a processor register and skip later reads. For a volatile object, each read in the source loads from the object’s address.
Merge two reads into one, or two writes into one. For a volatile object, two reads in the source give two reads.
Delete a write that is overwritten before any read, or a read whose value is unused. For a volatile object, both stay.
Reorder accesses. Two volatile accesses stay in source order, but a volatile access and an ordinary access may still be swapped.
Volatile has four established uses.
Device registers reached through memory-mapped I/O §4.35 (MMIO), in which the processor controls a peripheral by reading and writing memory addresses.
A flag shared between a program and a signal handler, a function the operating system runs when it delivers a signal to the program. For a signal that the program did not raise itself by calling
abortorraise, standard C lets the handler use an object that lives for the whole run, such as a global variable, only if the object is a lock-free §9.13 atomic object, or if the handler only assigns to it and it has typevolatile sig_atomic_t.A local variable changed between the
setjmpmacro and the matchinglongjmpcall, which together jump back to an earlier point in a program. Without volatile, the variable’s value after the jump is indeterminate.On a microcontroller §6.1 with one processor core, a flag shared between the main program and an interrupt handler §6.12, the function the hardware runs when a device signals an event. This widespread practice is correct only when each access to the flag is a single indivisible instruction and no other data must stay in order with the flag.
Volatile leaves three needs of concurrent code unmet, where concurrent code means two threads, or a thread and an interrupt handler, using the same data.
Indivisibility. An increment
count++on a volatile object is still three steps: read, add, write. Another thread or an interrupt handler can run between the read and the write. A 64-bit volatile object on a 32-bit processor is read with two 32-bit loads, and a write that lands between them yields a value that is half old and half new. An atomic operation §9.8, one that no other agent can observe half done, is needed instead.Mutual exclusion, the guarantee that at most one thread at a time runs a given section of code. Volatile makes no thread wait; a mutex §9.5, a lock that one thread at a time can hold, does.
Ordering between threads. The compiler keeps volatile accesses in order only relative to each other and may still move ordinary accesses across them. A processor that reorders memory operations may make one core’s writes visible to another core in a different order, and volatile emits no memory barrier §4.37, the instruction that would prevent that.
Other languages use the word differently. In Java, a write to a volatile field happens before every later read of that field, so Java’s volatile does order memory between threads. Microsoft’s C and C++ compiler has an option, /volatile:ms, that gives volatile accesses acquire and release ordering; that is a vendor extension, not standard C or C++.
Worked example
A microcontroller counts received packets in volatile uint32_t count, which holds 3. The main program executes count++, and the receive interrupt handler also executes count++. The main program’s increment compiles to three instructions: load count into a register, add 1, and store the register back.
The main program loads 3 into a register.
A packet arrives. The interrupt handler runs, loads 3, adds 1, stores 4 and returns.
The main program resumes, adds 1 to its register, , and stores 4.
Two increments ran, so the count should be . It is 4: one increment was lost. Volatile made every load and store happen, and that is exactly the sequence that lost the update; nothing stopped the handler from running between the load and the store. The repair is to make the increment indivisible: disable interrupts §6.11 around it, or use an atomic read-modify-write such as atomic_fetch_add from C11, the 2011 edition of the C standard.
A second example concerns order. A producer thread writes
data = 42;
ready = 1;
where only ready is volatile and both variables start at 0. The compiler may emit the store to ready first, because an ordinary access may be moved across a volatile one. A consumer thread on another core can then see ready equal to 1 and read data as 0. Making data volatile too fixes the compiler’s order but not the processor’s: on a processor that reorders memory operations, as many multi-core Arm processors may, the store to ready can still become visible to the other core first. The correct tool is an atomic flag: declare ready as atomic_int, write it with atomic_store_explicit(&ready, 1, memory_order_release), and read it with an acquire load. That pair creates the happens-before relation §9.10 that guarantees the consumer reads 42.
Stated precisely
The C standard states the contract of volatile in section 6.7.3, on type qualifiers: an object of volatile-qualified type may be modified in ways unknown to the implementation, so every expression that refers to it is evaluated strictly by the rules of the abstract machine, the idealized computer the standard uses to define what a program means. Section 5.1.2.3 counts volatile accesses among a program’s observable behavior, which every conforming compiler must preserve. What counts as one access is implementation-defined behavior §4.13: each compiler must document its choice. The standard does not say how many machine instructions one access becomes; for an aligned object, one whose address is a multiple of its size, no wider than the processor’s native word, compilers in practice use one load or one store of the object’s size, and device code relies on that platform behavior.
Between threads, the C11 memory model guarantees that a read sees a write, or a later write to the same object, when the write happens before the read. Only synchronization creates that happens-before relation between threads. Its main forms are an acquire load that reads a value written by a release store, the same pairing made with release and acquire fences, the unlocking of a mutex followed by a locking of the same mutex, and the creation and joining of threads. Volatile accesses create none of them. Section 5.1.2.4 of C11 defines a data race §9.3: two conflicting accesses in different threads, meaning accesses to the same memory location of which at least one is a write, where at least one access is not atomic and neither happens before the other. A data race is undefined behavior §4.12, so the standard places no requirement at all on what the program then does. Volatile accesses are not atomic, so two threads that use a volatile object without synchronization have a data race.
Limits and common mistakes
Volatile is neither a lock nor a memory barrier. Code that works with volatile on a single-core microcontroller can fail on a multi-core processor, where the hardware’s reordering becomes visible between cores.
Volatile does not make a wide access indivisible. To read a 64-bit counter that hardware keeps updating, on a 32-bit processor, a common pattern reads the high half, then the low half, then the high half again, and repeats if the two high halves differ.
Marking every shared variable volatile is not a fix. It forbids useful optimizations, slows the program, and still leaves indivisibility, mutual exclusion and ordering unprovided.
Volatile orders the compiler’s output, not the traffic on the bus. Whether a device sees two register writes in program order, and whether a register write is ordered against writes to ordinary memory, is decided by the processor architecture, and some cases need a barrier instruction.
A pointer to a volatile type made from a number does not prove that a device register exists at that address, or that the register accepts the access width the compiler uses. Those facts come from the chip’s documentation.
Questions answered
Does volatile provide mutual exclusion or inter-thread happens-before ordering?
Volatile provides neither mutual exclusion nor happens-before ordering between threads in C or C++. Mutual exclusion means that at most one thread at a time runs a section of code; volatile makes no thread wait, so two threads can be inside the same section at once. The happens-before relation is the guarantee that one thread’s earlier writes are visible to another thread’s later reads; in C11 and C++11 only synchronization creates it, through atomic operations or fences with release and acquire ordering, a mutex unlock followed by a lock of the same mutex, or thread creation and joining.
Volatile only obliges the compiler to perform each volatile access, in source order relative to other volatile accesses. The compiler may still move ordinary accesses across a volatile one, the processor may still make writes visible to other cores in a different order, and a read-modify-write such as count++ stays divisible, so an update can be lost. Two threads that use a volatile object without synchronization have a data race, which is undefined behavior. Use atomic operations or a mutex to coordinate threads. Java differs: there, a write to a volatile field happens before every later read of that field.
Related entries: Memory-mapped I/O (MMIO) (§4.35), Memory barrier (§4.37), Happens-before relation (§9.10), Data race (§9.3), Atomic operation (§9.8), Mutex (§9.5), Interrupt service routine (ISR) (§6.12). Further reading: [78].