Indivisible Operations, Memory Ordering, and Thread Handoffs with std::atomic

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Prompt

Explain what makes an operation atomic under the standard C++ memory model, and contrast std::atomic with coordinating shared state through std::mutex.

Ground your explanation in three concrete multithreaded scenarios without assuming that every std::atomic<T> specialization is lock-free:

  1. Standalone event counter: Multiple threads increment a shared integer that records event counts only and never signals readiness for any accompanying data.
  2. One-time producer-to-consumer handoff: A single writer thread populates an ordinary non-atomic message structure once, never mutates that structure afterward, and flips an atomic flag so a single reader thread knows it may safely inspect the fields.
  3. Multi-variable balance transfer: Funds move from one account balance to another while concurrent observers require the sum of both balances to remain invariant at every moment.

Use the first two scenarios to separate single-variable indivisibility from ordering guarantees across unrelated memory locations, and use the third scenario to show why chaining separate atomic operations does not automatically form an atomic transaction.

Scope & Expectations

  • Define C++ data races, undefined behavior, single-variable modification order, and why std::atomic<T> is not unconditionally lock-free for arbitrary types T.
  • Show why std::memory_order_relaxed read-modify-write increments suffice for a standalone counter yet fail to publish non-atomic fields without release-acquire synchronization.
  • Demonstrate how multi-step updates or invariants spanning multiple variables permit inconsistent intermediate observations even when individual loads and updates are atomic.
  • Provide clear engineering criteria—single-field vs. multi-field invariants, single-shot vs. repeated mutation, contention, and blocking—for choosing between std::atomic and std::mutex.

Step-by-step walkthrough

  1. Separate the two jobs: indivisible access vs. ordering other memory

    When two threads access the same plain (non-atomic) variable at the same time, at least one access writes to it, and no synchronization rule orders one before the other, the program has a data race. In C++, a data race is undefined behavior (UB)—meaning the language standard places zero limits on what happens, and the compiler may optimize your code assuming data races never occur. Without protection, concurrent access can also cause a torn read or write, where one thread observes half of an old 64-bit value mixed with half of a new one.

    Wrapping a variable in std::atomic<T> gives operations on that single variable two guarantees:

    1. Indivisibility (atomicity): Each individual load, store, or read-modify-write (RMW) (an operation that reads the current value and writes an updated value in one unbreakable step, like fetch_add) happens all at once—never torn, and never a data race.
    2. Single modification order: Every thread agrees on one sequence of values written to that specific atomic variable over time.

    Notice two things std::atomic<T> does not automatically promise:

    • It does not automatically order accesses to other variables. Controlling whether surrounding plain reads and writes can move across an atomic operation is a separate job, chosen via std::memory_order.
    • It is not guaranteed to be lock-free for every type T. A lock-free atomic uses direct CPU instructions so one paused thread cannot block others; for a large struct T, std::atomic<T> may silently use an internal lock under the hood. You can check std::atomic<T>::is_always_lock_free at compile time or x.is_lock_free() at run time (the standard unconditionally guarantees lock-freedom for std::atomic_flag).
  2. Pure counting: why relaxed atomics are enough

    Suppose four worker threads count events in a shared counter hits, and no other data depends on hits.

    With a plain std::int64_t hits = 0;, ++hits is actually three steps—load, add 1, store—so two threads can overwrite each other (and trigger UB):

    Initial state: hits = 5
    Thread 1: loads 5
    Thread 2: loads 5
    Thread 1: computes 5 + 1 -> stores 6
    Thread 2: computes 5 + 1 -> stores 6     <- two increments happened, but hits only rose by 1!
    

    Replacing ++hits with hits.fetch_add(1, std::memory_order_relaxed) makes the read-add-write one indivisible RMW operation:

    #include <atomic>
    #include <cstdint>
    #include <thread>
    #include <vector>
    
    std::atomic<std::int64_t> hits{0};
    
    void worker(int n) {
        for (int i = 0; i < n; ++i) {
            // One indivisible read-modify-write; no surrounding payload needs ordering
            hits.fetch_add(1, std::memory_order_relaxed);
        }
    }
    
    int main() {
        std::vector<std::thread> threads;
        for (int t = 0; t < 4; ++t) {
            threads.emplace_back(worker, 1'000'000);
        }
        for (auto& th : threads) {
            th.join();  // join() synchronizes worker completion with main()
        }
        return hits.load(std::memory_order_relaxed) == 4'000'000 ? 0 : 1;  // always 4,000,000
    }
    

    Why is std::memory_order_relaxed completely safe here?

    • Zero lost increments: C++ guarantees that every atomic RMW reads the most recent value in hits's modification order right before writing its new value (5 -> 6 -> 7), regardless of memory order.
    • No payload to publish: Because no thread uses hits as a signal that another struct or array is ready, we do not need fences around surrounding memory operations.
    • Clean final read: Returning from th.join() already synchronizes with the end of worker th, guaranteeing main() sees all 4,000,000 increments.
  3. Safe publication: how release and acquire build a visibility bridge

    Now change the job: one producer fills an ordinary, non-atomic Payload struct once and sets an atomic ready flag to true; one consumer waits until ready is true and then reads payload.

    If both threads used memory_order_relaxed on ready, only ready itself would be race-free! Either the compiler or a weakly ordered CPU (such as ARM) could reorder ready = true ahead of payload.price = 101.25, or hoist the consumer's read of payload.price ahead of checking ready—causing a data race (UB) on payload. (Note: marking variables volatile does not fix this in C++; volatile is for special hardware memory like device registers, not thread synchronization.)

    To publish payload safely, pair a release store with an acquire load:

    • Release store (memory_order_release): No earlier reads or writes in the producer thread may be reordered after this store.
    • Acquire load (memory_order_acquire): No later reads or writes in the consumer thread may be reordered before this load.
    • Synchronizes-with and happens-before: When an acquire load reads the true written by a release store, the store synchronizes with the load, creating a happens-before bridge: every write the producer did before setting ready is guaranteed to be visible to every read the consumer does after seeing ready == true.
    Producer thread                                  Consumer thread
    ------------------------------                   ------------------------------------
    1. payload.id = 7;
    2. payload.price = 101.25;
    3. payload.symbol = "XYZ";
    4. ready.store(true, release)  ---syncs-with---> 5. ready.load(acquire) observes true
       [barrier: 1-3 stay above 4]                      [barrier: 6 stays below 5]
                                                     6. reads payload.price -> always 101.25
    
    #include <atomic>
    #include <string>
    
    struct Payload {
        int id;
        double price;
        std::string symbol;
    };
    
    Payload payload;                  // Ordinary non-atomic struct
    std::atomic<bool> ready{false};   // Atomic publication flag
    
    void producer() {
        payload.id = 7;
        payload.price = 101.25;
        payload.symbol = "XYZ";
        ready.store(true, std::memory_order_release);  // Publishes writes above
    }
    
    double consumer() {
        while (!ready.load(std::memory_order_acquire)) {
            // Spin until ready is true (in C++20, ready.wait(false, acquire) avoids busy-spinning)
        }
        // Guaranteed happens-before: id == 7, price == 101.25, symbol == "XYZ"
        return payload.price;
    }
    
  4. Compare the C++ memory orders at a glance

    Every std::memory_order keeps operations on the atomic variable itself indivisible; they only differ in how strictly they fence surrounding memory accesses:

    Memory order   Applies to    Rule for surrounding reads & writes          Typical use case
    -------------  ------------  -------------------------------------------  ----------------------------------
    relaxed        load/store/   No ordering on other variables               Pure counters, stats, IDs
                   RMW
    release        store / RMW   Earlier accesses cannot sink below this op   Producer publishing data
    acquire        load / RMW    Later accesses cannot float above this op    Consumer reading published data
    acq_rel        RMW only      Both acquire (on read) + release (on write)  Reference-count decrement, CAS
    seq_cst        load/store/   Acquire/release PLUS one global timeline     Default; cross-flag protocols
                   RMW           shared by all seq_cst operations
    

    Why does the default memory_order_seq_cst (sequential consistency) exist if release/acquire already handles producer-consumer publication? Because release/acquire only connects a writer of flag X to a reader of that same flag X. Suppose two threads write to different atomic flags (x = 0, y = 0) and then read the other thread's flag:

    Initially: atomic<int> x = 0, y = 0
    Thread 1: x.store(1);  r1 = y.load();
    Thread 2: y.store(1);  r2 = x.load();
    

    With release stores and acquire loads, real CPUs (even x86, due to per-core store buffers) can finish with r1 == 0 and r2 == 0! With seq_cst, all seq_cst operations share one global order: whichever store lands first in that global order must be seen by the other thread's load, making r1 == 0 && r2 == 0 impossible.

  5. Why a sequence of atomic steps is NOT a transaction

    Making individual steps atomic does not stop another thread from running between two steps. This shows up in two classic ways:

    1. Check-then-act on a single atomic variable. Suppose limit = 10 and count = 9, and two threads run if (count.load() < limit) count.fetch_add(1);. Both threads load 9, both pass < 10, and both add 1, pushing count to 11! To keep the check and update together, use a compare-and-swap (CAS) loop (compare_exchange_weak), which updates count from cur to cur + 1 only if count is still cur (and reloads cur automatically if another thread changed it):

    #include <atomic>
    
    bool try_increment(std::atomic<int>& count, int limit) {
        int cur = count.load(std::memory_order_relaxed);
        while (cur < limit) {
            // _weak may occasionally fail spuriously on CPUs like ARM, which is fine inside a while loop
            if (count.compare_exchange_weak(cur, cur + 1, std::memory_order_relaxed)) {
                return true;
            }
            // On failure, cur now holds the latest value of count; loop re-checks cur < limit
        }
        return false;
    }
    

    2. An invariant across two variables. An invariant is a consistency rule across state that every observer should see as true—for example, two account balances a = 100 and b = 0 whose sum a + b must always equal 100. Even if a and b are std::atomic<long long> with default seq_cst, transferring 30 takes two separate operations, so a concurrent auditor can observe a broken total:

    Initial state: a = 100, b = 0   (invariant: a + b == 100)
    Transfer thread:   a.fetch_sub(30);       b.fetch_add(30);
    Auditor thread:    sum = a.load() + b.load();
    
    Interleaving A (missing money):
      1. Transfer runs a.fetch_sub(30)   -> a = 70, b = 0
      2. Auditor reads a (70) + b (0)    -> observes sum = 70!
      3. Transfer runs b.fetch_add(30)   -> a = 70, b = 30
    
    Interleaving B (phantom money):
      1. Auditor reads a                 -> sees 100
      2. Transfer runs both steps        -> a = 70, b = 30
      3. Auditor reads b                 -> sees 30, observes sum = 130!
    

    To make a multi-field update appear indivisible to readers, protect the whole critical section (the block of code reading or updating the related fields) with a std::mutex in both writers and readers:

    #include <mutex>
    
    struct Accounts {
        std::mutex m;
        long long a = 100;  // Invariant: a + b == 100 (guarded by m)
        long long b = 0;
    };
    
    void transfer(Accounts& acc, long long amount) {
        std::lock_guard<std::mutex> lock(acc.m);
        acc.a -= amount;
        acc.b += amount;
    }
    
    long long total(Accounts& acc) {
        std::lock_guard<std::mutex> lock(acc.m);
        return acc.a + acc.b;  // Always observes 100
    }
    
  6. Choosing between `std::atomic` and `std::mutex`

    Before picking a primitive, verify three architectural properties—whether the variable guards external fields, whether writers mutate a shared object more than once, and whether consistency spans more than one variable—then match the primitive to that scope:

    • Scope: std::atomic protects one variable for one operation; std::mutex groups any number of variables and statements into one mutually exclusive critical section (unlock() acts as a release and the next lock() acts as an acquire).
    • Blocking and deadlocks: A lock-free atomic never puts threads to sleep and cannot deadlock; a std::mutex blocks waiting threads and can deadlock if multiple locks are acquired in inconsistent orders.
    • Contention reality check: Lock-free does not mean "infinitely scalable." If 8 threads hammer hits.fetch_add(1) in a tight loop, the CPU cores still bounce a single cache line back and forth; accumulating into a local variable per thread and adding once at the end beats both a contended atomic and a contended mutex.
    Requirement                                          Right tool
    ---------------------------------------------------  -----------------------------------------------
    Single counter/metric, publishes no other data       std::atomic + fetch_add(memory_order_relaxed)
    One-shot ready flag publishing an immutable payload  std::atomic<bool> with release store / acquire load
    Conditional update on one variable (e.g. cap at N)   std::atomic + compare_exchange_weak loop
    Invariant across 2+ fields or multi-step updates     std::mutex held by every writer AND every reader
    

Intuition & how it works

Think of std::atomic like a mechanical stadium turnstile with a built-in clicker, and std::mutex like a single-occupancy room with a lock on the door. Two fans pushing through the turnstile at the same moment never corrupt the counter—it clicks cleanly from 5 to 6 to 7—and pairing an atomic ready sign with release/acquire ordering acts like a rule that the clerk must finish placing your order on the counter before flipping the "Order Ready" sign. However, a turnstile only guards one variable for one step; if you need to move cash between two separate ledgers without an auditor catching them mid-transfer, you need the locked room (std::mutex) so nobody looks inside until both ledgers are updated.

Beginners run into two opposite traps here. First, assuming a plain ++counter is already safe—in C++, unsynchronized concurrent reads and writes to a plain variable form a data race, which is undefined behavior (the program has no guaranteed meaning at all). Second, assuming that making variables std::atomic automatically makes multi-step code thread-safe, or that a relaxed atomic ready flag safely publishes a non-atomic struct—without memory-ordering barriers, the compiler or CPU can reorder the struct accesses past the flag!

Walk through the three core cases with concrete numbers:

  1. Pure counter (hits = 5): Two threads calling hits.fetch_add(1, std::memory_order_relaxed) each perform an indivisible read-modify-write (RMW) (reading the old value and writing the new value in one unbreakable step), advancing hits 5 -> 6 -> 7 with zero lost updates.
  2. One-shot publication (Payload{id = 7, price = 101.25}): The producer writes payload.price = 101.25 and calls ready.store(true, std::memory_order_release); when the consumer's ready.load(std::memory_order_acquire) reads true, the store synchronizes with the load, guaranteeing the consumer sees 101.25.
  3. Two-balance invariant (a = 100, b = 0, sum 100): Even with std::atomic, running a.fetch_sub(30) followed by b.fetch_add(30) lets a concurrent a.load() + b.load() read 70 + 0 = 70 or 100 + 30 = 130; holding a std::mutex in both transfer and total keeps the observed sum at 100.

Key points

  • Atomicity and memory ordering are separate knobs: Atomicity prevents torn reads/writes (seeing half of an old value and half of a new one) and gives one atomic variable a single modification order (one timeline of writes agreed on by all threads), while std::memory_order controls whether other memory reads and writes can move across that atomic operation.
  • Data races are undefined behavior: Conflicting unsynchronized accesses to an ordinary C++ variable do not merely produce "slightly stale values"—the compiler may optimize assuming races cannot happen.
  • Relaxed atomics suffice for standalone counters: fetch_add(1, std::memory_order_relaxed) never loses increments because every RMW reads the latest value in the variable's modification order, and std::thread::join() makes final totals visible afterward.
  • Release/acquire establishes happens-before: A memory_order_release store prevents earlier writes from sinking below it, and a memory_order_acquire load prevents later reads from floating above it; when the acquire load observes the release store, every pre-store write happens before (is guaranteed visible to) every post-load read.
  • seq_cst adds one global timeline: Default memory_order_seq_cst adds a single total order across all seq_cst operations, which is needed when threads write separate flags and read each other's flags, though release/acquire is enough for producer-to-consumer publication.
  • Atomics do not compose into transactions: Check-then-act on one atomic needs a compare-and-swap (CAS) loop (compare_exchange_weak, which updates the variable only if it still matches the expected value), and an invariant (a consistency rule that must always hold) spanning multiple variables requires a std::mutex locked by both writers and readers.
  • std::atomic<T> is not always lock-free: A lock-free type uses hardware atomic instructions without internal locks, whereas a large std::atomic<BigStruct> may silently fall back to an internal lock; verify with std::atomic<T>::is_always_lock_free or .is_lock_free().

Common mistakes

  • Using memory_order_relaxed on a publication flag: The flag itself has no data race, so tests on x86 may appear to pass, while compiler instruction scheduling or an ARM CPU reorders the non-atomic payload writes/reads into undefined behavior.
  • Treating volatile as thread synchronization: In C++, volatile is designed for memory-mapped hardware registers; it neither makes operations atomic nor establishes happens-before ordering between threads.
  • Splitting an update across two atomic calls: Writing if (count.load() < limit) count.fetch_add(1) allows another thread to slip between the load() and fetch_add(), exceeding limit.
  • Making every struct field std::atomic to protect a multi-field invariant: Readers can still see field a from after an update and field b from before it (70 + 0 = 70 or 100 + 30 = 130).
  • Locking the mutex in writers while reading "just to check" without locking: An unlocked read of non-atomic variables while another thread writes under a mutex is still a data race (UB).
  • Assuming lock-free always means fast under heavy contention: Eight threads tight-looping on one atomic counter serialize on cache-line ownership; thread-local counters merged at the end avoid that bottleneck.

Follow-up questions

  • Even though counter.load() and counter.store(...) are each atomic on their own, why can counter.store(counter.load() + 1) still drop updates under concurrency? Because counter.load() and counter.store(...) execute as two distinct atomic operations separated by an unprotected window where other threads may interleave. If counter starts at 5, Thread 1 can load() 5 and Thread 2 can also load() 5 before either writes back; both then compute 5 + 1 and store(6), collapsing two increments into +1. Preserving every increment requires a single read-modify-write instruction such as counter.fetch_add(1) (or ++counter), which reads the latest value in the variable's modification order and writes the updated value in one unbreakable step.
  • How must the synchronization design change if the writer updates the shared message structure multiple times instead of writing it only once? A one-way boolean flag only guards the initial write: if the writer begins overwriting payload with version 2 while the reader is halfway through reading version 1, the ordinary payload fields suffer a concurrent read/write data race. The most direct solution is wrapping both writer updates and reader copies inside a std::mutex. Lock-free designs instead avoid concurrent access to the same slot—either via a two-way state protocol (EMPTY -> FULL with a writer release store, then FULL -> EMPTY with a reader release store once copied), a single-producer/single-consumer ring buffer, or swapping an atomic pointer (std::atomic<std::shared_ptr<const Payload>> in C++20) to freshly allocated immutable snapshots.

Follow-up questions

Similar questions

More Millennium interview questions

All 11 Millennium questions →