Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 135 ยท Advanced C

volatile and C11 Atomics

Understand what volatile really guarantees in C, why it does not make code thread safe, and how C11 atomics, compare-exchange and memory orders solve data races.

Compilers are allowed to rewrite your program as long as the result looks the same to a single thread. They keep values in registers, merge repeated reads, reorder statements and delete writes nobody seems to use. That freedom is why C is fast, and it is also why two situations need special tools: memory that changes outside the program's control (hardware registers, signal handlers), and memory shared between threads.

C has a keyword for the first situation (volatile) and a library for the second (<stdatomic.h>). Programmers confuse them constantly. This lesson explains what each one promises, what it does not, and how memory ordering works when threads need to hand data to one another.

What volatile means

When an object is volatile, every read and write in the source is an observable side effect. The compiler must perform each access exactly as written: it may not cache the value in a register across statements, merge two reads into one, or remove a write because "nobody reads it".

C
volatile int ready = 0;

while (!ready) {
    /* spin */
}

Without volatile, the compiler can notice that nothing in the loop changes ready, read it once, and turn the loop into while (1) {} or skip it entirely. With volatile, ready is reloaded on every iteration.

There are three classic uses:

  1. Memory-mapped hardware registers on embedded systems. Reading a status register may clear a flag; writing a control register starts a motor. Every access matters.
  2. Variables changed by a signal handler. The handler can run between any two statements of the main program (see Signals).
  3. Variables modified between setjmp and longjmp (see setjmp and longjmp).

The standard guarantees one more thing for a specific type: volatile sig_atomic_t, from <signal.h>, is an integer type that can be read and written in a single uninterruptible step with respect to signals. It is the only type (besides lock-free atomics) a handler may portably assign to.

C volatile sig_atomic_t and a signal handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Where volatile syntax gets confusing

Like const, the position of volatile in a pointer declaration matters:

C
volatile int *a;          /* pointer to a volatile int: the DATA is volatile      */
int *volatile b;          /* volatile pointer to int: the POINTER is volatile     */
volatile uint32_t *const reg = (volatile uint32_t *)0x40021000u;
                          /* constant address of a hardware register (embedded)   */

The last form is the idiom you will see in microcontroller code, where reg can never be re-pointed and every read or write of *reg becomes a real load or store. Read the pointer-qualifier rules again in const and Pointers; they apply to volatile the same way.

What volatile does NOT do

This is the most important part of the lesson. volatile is not a synchronization tool:

  • It does not make an operation atomic. volatile int counter; counter++; is still a read, an add and a write; two threads can interleave and lose updates.
  • It does not order accesses relative to other memory. A CPU or compiler may still move non-volatile accesses across a volatile one, and the hardware may reorder stores.
  • It does not insert memory barriers, so another core may see writes in a different order.
  • Two threads accessing the same non-atomic variable, where at least one writes, is a data race, which is undefined behavior whether or not the variable is volatile (see Undefined Behavior).

Rule of thumb: use volatile for hardware and signal handlers, and use atomics or mutexes for threads.

C11 atomics

<stdatomic.h> (C11) provides types and operations that the hardware performs as one indivisible step, with well-defined interaction between threads. An atomic read or write is never torn, and an atomic read-modify-write cannot lose another thread's update. If your implementation doesn't support them it defines __STDC_NO_ATOMICS__ (see Modern C).

The common types are atomic_int, atomic_long, atomic_bool, atomic_size_t, atomic_flag, plus the general _Atomic(T) qualifier or _Atomic T for any type: _Atomic(struct node *) head;.

Operation What it does
atomic_load(&a), atomic_store(&a, v) Read or write the whole value atomically
atomic_fetch_add(&a, n) Add n, return the old value (also _sub, _and, _or, _xor)
atomic_exchange(&a, v) Store v, return the old value
atomic_compare_exchange_strong(&a, &expected, desired) If a == expected store desired and return true; otherwise copy the current value into expected and return false
atomic_flag_test_and_set(&f) Set the flag, return its previous state

Plain operators work too (a++, a += 5, a = 3) and mean the sequentially consistent version of the matching function. Here is the lost-update problem from Multithreading, solved with no mutex:

C An atomic counter shared by four threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The result is always exactly 400000. With a plain int (or a volatile int) it would usually be smaller, and the program would be undefined behavior.

compare-exchange loops

atomic_fetch_add covers simple counters. For anything else (update a maximum, push onto a lock-free stack, multiply) you use a compare-exchange loop: read the current value, compute the new one, and try to swap it in only if nobody changed it meanwhile. If someone did, the call fails, hands you the fresh value in expected, and you try again.

C Tracking a shared maximum with compare-exchange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The largest value any thread records is 9000 + 999 = 9999, so that is always the result, however the threads interleave. _weak may fail spuriously (even if the values are equal) on some processors, which is fine inside a loop and can be faster; use _strong outside a loop.

Warning: Lock-free code with compare-exchange can suffer the ABA problem: a value changes from A to B and back to A, and your compare-exchange cannot tell. It matters mostly for pointer-based structures like stacks. Prefer a mutex unless you have measured a need for lock-free code.

Memory order: the second argument you didn't know about

Every atomic function has an _explicit version taking a memory order, such as atomic_load_explicit(&a, memory_order_acquire). The plain versions use the strongest order, memory_order_seq_cst.

Why does order matter at all? Both the compiler and the CPU reorder ordinary reads and writes. If thread A writes some data and then sets a flag, thread B might see the flag as set while the data write is not yet visible. Memory orders say how much ordering an atomic operation imposes on the other memory accesses around it.

Order Guarantee
memory_order_relaxed The operation is atomic, nothing else. No ordering of surrounding accesses. Good for counters nobody uses to publish data
memory_order_release (stores) All writes before this store become visible to a thread that acquires the same variable and sees this value
memory_order_acquire (loads) Pairs with release: after seeing the released value, you also see everything written before it
memory_order_acq_rel Both, for read-modify-write operations
memory_order_seq_cst Acquire/release plus one global order that all threads agree on. The default, easiest to reason about

A release store and an acquire load on the same variable form a handshake:

sequenceDiagram
    participant P as Producer thread
    participant F as ready (atomic)
    participant C as Consumer thread
    P->>P: payload = 42 (plain write)
    P->>F: store(1, release)
    C->>F: load(acquire) sees 1
    Note over C: guaranteed to see payload == 42
    C->>C: read payload

Release publishes everything written before it; an acquire load that sees the stored value gets all of it.

C Publishing data with release and acquire

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The sum is always 110 (11 + 22 + 33 + 44). If both operations were memory_order_relaxed, the consumer could see ready == true and still read stale values from payload on weakly ordered CPUs such as ARM, even though x86 would usually hide the bug. That is why atomics bugs are so hard to test: they can sit unnoticed until you run on different hardware or a more aggressive optimizer.

If you are unsure which order to use, leave out _explicit and take seq_cst. Reach for relaxed only for statistics counters, and acquire/release when you understand the handshake above.

atomic_flag and a spinlock

atomic_flag is the one atomic type guaranteed to be lock-free on every implementation. Its only operations are test-and-set and clear, enough to build a simple spinlock:

C
static atomic_flag lock = ATOMIC_FLAG_INIT;

void acquire(void) {
    while (atomic_flag_test_and_set_explicit(&lock, memory_order_acquire)) {
        /* busy-wait */
    }
}

void release(void) {
    atomic_flag_clear_explicit(&lock, memory_order_release);
}

Spinlocks waste CPU while waiting and misbehave when a thread holding the lock gets descheduled, so ordinary code is better served by pthread_mutex_t or mtx_t (Multithreading). Use a spinlock only for very short critical sections.

Choosing the right tool

Situation Use
Hardware register, memory-mapped I/O volatile pointer
Flag set by a signal handler volatile sig_atomic_t
Counter or flag shared between threads _Atomic / atomic_*
Several related values updated together A mutex
Data handed from one thread to another Atomic flag with release/acquire, or a mutex or condition variable

You can combine them: a hardware register shared by interrupts and threads on a microcontroller might be both volatile and accessed through compiler-specific atomics. But as a beginner's rule, volatile is never the answer to "my threads disagree about this variable".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the volatile qualifier guarantee?

    volatile only constrains the compiler's treatment of that object's accesses. It adds no atomicity and no inter-thread ordering.
  2. 2. Two threads each run volatile int n; n++; 100000 times. What is the result?

    n++ is a separate load, add and store, and unsynchronized access from two threads is a data race. volatile does not change that. Use atomic_fetch_add or a mutex.
  3. 3. After a failed atomic_compare_exchange_strong(&a, &expected, desired), what is in expected?

    On failure the call writes the value it actually found into expected, which is what makes retry loops short.
  4. 4. A producer writes data and then does a release store of a flag. What must the consumer use to be sure it sees the data?

    A release store pairs with an acquire load. Once the load sees the released value, every write made before the store is visible too.
  5. 5. Which type is the right one for a flag set inside a signal handler?

    sig_atomic_t can be accessed as a single uninterruptible unit with respect to signals, and volatile forces real loads and stores.

Summary

  • volatile forces the compiler to perform every access to an object exactly as written. Use it for memory-mapped hardware, volatile sig_atomic_t signal flags and variables used across longjmp.
  • volatile does not provide atomicity, ordering or thread safety. Concurrent unsynchronized access is a data race regardless.
  • <stdatomic.h> offers atomic_int, _Atomic(T), atomic_fetch_add, atomic_exchange and atomic_compare_exchange_* for lock-free thread-safe updates.
  • Compare-exchange loops retry until no other thread interferes; watch for the ABA problem.
  • Memory orders control visibility of surrounding writes: relaxed (none), release/acquire (publish/consume), seq_cst (default, simplest).
  • When in doubt, use a mutex or the default seq_cst atomics.

Next: Memory-Mapped Files