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:
- Standalone event counter: Multiple threads increment a shared integer that records event counts only and never signals readiness for any accompanying data.
- 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.
- 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 typesT. - Show why
std::memory_order_relaxedread-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::atomicandstd::mutex.
Step-by-step walkthrough
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:- 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. - 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 structT,std::atomic<T>may silently use an internal lock under the hood. You can checkstd::atomic<T>::is_always_lock_freeat compile time orx.is_lock_free()at run time (the standard unconditionally guarantees lock-freedom forstd::atomic_flag).
- 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
Pure counting: why relaxed atomics are enough
Suppose four worker threads count events in a shared counter
hits, and no other data depends onhits.With a plain
std::int64_t hits = 0;,++hitsis actually three steps—load, add1, 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
++hitswithhits.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_relaxedcompletely 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
hitsas 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 workerth, guaranteeingmain()sees all4,000,000increments.
- Zero lost increments: C++ guarantees that every atomic RMW reads the most recent value in
Safe publication: how release and acquire build a visibility bridge
Now change the job: one producer fills an ordinary, non-atomic
Payloadstruct once and sets an atomicreadyflag totrue; one consumer waits untilreadyistrueand then readspayload.If both threads used
memory_order_relaxedonready, onlyreadyitself would be race-free! Either the compiler or a weakly ordered CPU (such as ARM) could reorderready = trueahead ofpayload.price = 101.25, or hoist the consumer's read ofpayload.priceahead of checkingready—causing a data race (UB) onpayload. (Note: marking variablesvolatiledoes not fix this in C++;volatileis for special hardware memory like device registers, not thread synchronization.)To publish
payloadsafely, 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
truewritten by a release store, the store synchronizes with the load, creating a happens-before bridge: every write the producer did before settingreadyis guaranteed to be visible to every read the consumer does after seeingready == 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; }- Release store (
Compare the C++ memory orders at a glance
Every
std::memory_orderkeeps 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 operationsWhy does the default
memory_order_seq_cst(sequential consistency) exist ifrelease/acquirealready handles producer-consumer publication? Becauserelease/acquireonly connects a writer of flagXto a reader of that same flagX. 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
releasestores andacquireloads, real CPUs (even x86, due to per-core store buffers) can finish withr1 == 0andr2 == 0! Withseq_cst, allseq_cstoperations share one global order: whichever store lands first in that global order must be seen by the other thread's load, makingr1 == 0 && r2 == 0impossible.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 = 10andcount = 9, and two threads runif (count.load() < limit) count.fetch_add(1);. Both threads load9, both pass< 10, and both add1, pushingcountto11! To keep the check and update together, use a compare-and-swap (CAS) loop (compare_exchange_weak), which updatescountfromcurtocur + 1only ifcountis stillcur(and reloadscurautomatically 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 = 100andb = 0whose suma + bmust always equal100. Even ifaandbarestd::atomic<long long>with defaultseq_cst, transferring30takes 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::mutexin 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 }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::atomicprotects one variable for one operation;std::mutexgroups any number of variables and statements into one mutually exclusive critical section (unlock()acts as a release and the nextlock()acts as an acquire). - Blocking and deadlocks: A lock-free atomic never puts threads to sleep and cannot deadlock; a
std::mutexblocks 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- Scope:
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:
- Pure counter (
hits = 5): Two threads callinghits.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), advancinghits5 -> 6 -> 7with zero lost updates. - One-shot publication (
Payload{id = 7, price = 101.25}): The producer writespayload.price = 101.25and callsready.store(true, std::memory_order_release); when the consumer'sready.load(std::memory_order_acquire)readstrue, the store synchronizes with the load, guaranteeing the consumer sees101.25. - Two-balance invariant (
a = 100, b = 0, sum100): Even withstd::atomic, runninga.fetch_sub(30)followed byb.fetch_add(30)lets a concurrenta.load() + b.load()read70 + 0 = 70or100 + 30 = 130; holding astd::mutexin bothtransferandtotalkeeps the observed sum at100.
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_ordercontrols 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, andstd::thread::join()makes final totals visible afterward. - Release/acquire establishes happens-before: A
memory_order_releasestore prevents earlier writes from sinking below it, and amemory_order_acquireload 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_cstadds one global timeline: Defaultmemory_order_seq_cstadds a single total order across allseq_cstoperations, which is needed when threads write separate flags and read each other's flags, thoughrelease/acquireis 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 astd::mutexlocked 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 largestd::atomic<BigStruct>may silently fall back to an internal lock; verify withstd::atomic<T>::is_always_lock_freeor.is_lock_free().
Common mistakes
- Using
memory_order_relaxedon 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
volatileas thread synchronization: In C++,volatileis 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 theload()andfetch_add(), exceedinglimit. - Making every struct field
std::atomicto protect a multi-field invariant: Readers can still see fieldafrom after an update and fieldbfrom before it (70 + 0 = 70or100 + 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()andcounter.store(...)are each atomic on their own, why cancounter.store(counter.load() + 1)still drop updates under concurrency? Becausecounter.load()andcounter.store(...)execute as two distinct atomic operations separated by an unprotected window where other threads may interleave. Ifcounterstarts at5, Thread 1 canload()5and Thread 2 can alsoload()5before either writes back; both then compute5 + 1andstore(6), collapsing two increments into+1. Preserving every increment requires a single read-modify-write instruction such ascounter.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
payloadwith version 2 while the reader is halfway through reading version 1, the ordinarypayloadfields suffer a concurrent read/write data race. The most direct solution is wrapping both writer updates and reader copies inside astd::mutex. Lock-free designs instead avoid concurrent access to the same slot—either via a two-way state protocol (EMPTY -> FULLwith a writerreleasestore, thenFULL -> EMPTYwith a readerreleasestore 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
- 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?
- How must the synchronization design change if the writer updates the shared message structure multiple times instead of writing it only once?
Similar questions
- Diagnosing Silent Exit in an Async Python HTTP Script
- Validation Harness for an LLM Ticket-Routing Agent
- C++ Compilation Pipelines and Optimizer Semantics Across GCC, Clang, and LLVM
- Thread-Safe Shared State with C++ std::mutex
- Product Manager Recruiter Screen: Fit, Strategy, and Motivation
- Risk-Governed AI System for Portfolio Rebalancing
More Millennium interview questions
- Technical Project Deep Dive and Toughest Implementation Problem Medium
- C++ Compilation Pipelines and Optimizer Semantics Across GCC, Clang, and LLVM Medium
- Thread-Safe Shared State with C++ std::mutex Medium Pro
- Product Manager Recruiter Screen: Fit, Strategy, and Motivation Easy Pro
- Diagnosing Silent Exit in an Async Python HTTP Script Medium Pro
- Risk-Governed AI System for Portfolio Rebalancing Medium Pro
- Validation Harness for an LLM Ticket-Routing Agent Medium Pro
- Translating Technical Work for Stakeholders and Trading ML Fit Medium Pro
- Short-Horizon Equity Return Forecasting Pipeline Medium Pro
- Streaming Paginated Order Ingestion to CSV Medium Pro