</>EmbeddedInterview

Does volatile make a variable thread-safe or atomic?

MediumEmbedded C

Short answer: No. volatile only stops the compiler from caching, merging or removing accesses. It does not make read-modify-write operations atomic, does not make multi-word accesses atomic, and does not stop the CPU (or other cores, caches and bus) from reordering memory accesses.

Three ways volatile is not enough

  1. Read-modify-write: volatile uint32_t count; count++; compiles to load, add, store. An ISR that also increments count between the load and the store loses one increment.
  2. Multi-word data: a 64-bit volatile uint64_t ticks on a 32-bit Cortex-M is read with two 32-bit loads. If the timer ISR updates it between them (e.g. when the low word wraps from 0xFFFFFFFF to 0), the reader sees a torn value that is off by about 4 billion.
  3. Ordering between variables: writing data = x; ready = true; with both volatile guarantees the compiler keeps the order, but on a multi-core system or with write buffers, another core may see ready before data without a barrier (__DMB(), or C11 release/acquire).

The right tools

Situation Tool
Main code ↔ ISR on a single-core MCU short critical section (disable/mask interrupts), or a single aligned 32-bit word that only one side writes
Counters/flags shared between threads C11 <stdatomic.h> (atomic_fetch_add), compiled to LDREX/STREX on Cortex-M3+
Complex shared data between tasks RTOS mutex, or message queues (do not share at all)
Multi-core / DMA ordering memory barriers or acquire/release atomics, plus cache maintenance
Linux kernel atomic_t, READ_ONCE/WRITE_ONCE, spinlocks, RCU

Reading a 64-bit counter safely without disabling interrupts:

uint64_t read_ticks64(void)
{
    uint32_t hi1, lo, hi2;
    do {
        hi1 = g_ticks_hi;          /* volatile, updated by the ISR */
        lo  = g_ticks_lo;
        hi2 = g_ticks_hi;
    } while (hi1 != hi2);          /* retry if the ISR changed the high word meanwhile */
    return ((uint64_t)hi1 << 32) | lo;
}

Interview line: "volatile is for hardware and ISR visibility, atomics and locks are for concurrency. You usually need volatile and something else."