← Runtimes
Runtimes

C++ atomics, memory order, and data races

A data race is undefined behavior; atomics and memory order make sharing defined.

Safe shared state needs both defined accesses and a protocol that preserves the meaning of the data.

Outcome

Explain why a data race is undefined behavior, choose the atomic operation that makes an update indivisible, and publish data from one thread to another with release and acquire.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Data race
Two threads access the same memory location, at least one writes, at least one access is not atomic, and nothing orders them. The program’s behavior is undefined.
std::atomic<T>
A live, properly initialized atomic object supports indivisible atomic accesses. Concurrent atomic accesses do not race with each other; related non-atomic data and multi-operation invariants still need a protocol.
compare_exchange_weak
Compares the current value with expected; on success stores desired, and on failure replaces expected with the observed value. Weak can fail spuriously even on a match, so a retry may be needed.
memory_order
How an atomic operation orders the surrounding ordinary reads and writes: relaxed (none), release and acquire (publication), or seq_cst (the default, one total order).
Happens-before
An ordering between evaluations. An acquire operation reading a matching release publication can establish it, ordering earlier producer writes before later consumer reads.

Atomic access and shared-state protocols

C++ distinguishes conflicting accesses to one memory location from a logical inconsistency spread across several values. A data race involves conflicting unordered accesses in different threads, at least one a write and at least one non-atomic, and gives undefined behavior. An initialized, live atomic object provides indivisible accesses that do not race with one another.

Atomicity applies to the chosen operation. A sequence of atomic operations still needs reasoning about interleaving, and ordinary data associated with an atomic flag needs an ordering and lifetime protocol. Memory order specifies synchronization guarantees; it does not turn an arbitrary multi-step calculation or a group of fields into one indivisible action.

01Data races

A racy flag leaves no defined execution contract

A C++ stock quote service waits for a flag that its price-feed thread sets once the feed has connected. In the debug build it works; in the release build the service never starts serving, and no line of the source changed. What did the optimizer assume, and what do std::atomic and memory_order promise instead?

The plain startup flag has an unordered read/write pair across threads. That data race leaves no required program behavior for an optimizer to preserve. One possible transformation is to retain an initial flag load instead of repeating it. The reduced probe sleeps for 50 ms before setting the flag, first calls an unoptimized wait, then a function with GCC’s O2 attribute. Its recorded output shows a failure; it does not reveal the generated instructions.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <thread>

// The quote service's startup: wait until the price feed has connected.
bool ready = false;  // written by the feed thread, read by the service: a data race

void wait_debug_build() {
    while (!ready) {
    }
}

[[gnu::optimize("O2")]] void wait_release_build() {
    while (!ready) {
    }
}

void run(const char* name, void (*wait)()) {
    ready = false;
    std::thread feed([] {  // connects, then sets the flag
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        ready = true;
    });
    wait();
    std::printf("%s: saw the flag\n", name);
    feed.join();
}

int main() {
    std::thread([] {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::printf("release build: still spinning after 1 s\n");
        std::fflush(stdout);
        std::_Exit(0);
    }).detach();
    run("debug build", wait_debug_build);
    run("release build", wait_release_build);
}
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
g++ -std=c++23 -Wall -Wextra -pedantic main.cpp -o main && ./main
Assume the illustration’s release wait retains its first false flag read instead of loading again. What does that authored model predict?

02Atomic operations

Each operation is indivisible; a sequence of them is not

Making a variable std::atomic makes each operation on it race-free. An update written as a load followed by a store is still two operations, and another thread can change the value between them. Use a single read-modify-write operation, or retry with compare_exchange when the new value depends on the old one in a way no single operation expresses.

std::atomic<int> operations
OperationIndivisible effectTypical use
load() / store(v)Read or write the whole valueFlags, published pointers
exchange(v)Write v and return the old valueTake ownership, reset and read
fetch_add(n)Add n and return the old valueCounters, ticket numbers
compare_exchange_weak(e, v)If the value is e, write v; else copy it into eMaximum, minimum, any computed update
wait(old) / notify_one()Block while the value equals old; wake a waiterWaiting without spinning (C++20)
Two feed threads raise the day high, a std::atomic<int> in cents, with: if (p > high.load()) high.store(p). The high is 18200; one thread offers 18400 and the other 18300. Which final values are possible?

03Memory order

Release and acquire publish what was written before

Startup needs the price as well as the ready bit. Here one producer writes the opening price once, then stores true with release. An acquire load or wait that reads that publication orders the earlier price write before the consumer’s later read. There must be no unordered rewrite while the consumer reads. Default seq_cst loads/stores include acquire/release and participate in a total order of seq_cst operations. Relaxed accesses remain atomic but supply no such publication edge; they can suit an independent statistic that publishes no other data.

Choosing a memory order
OrderGuaranteeFits
relaxedThe operation is indivisible; no ordering of other memoryStatistics counters
release (store)Earlier writes become visible to an acquire load that reads this valuePublishing a flag or pointer
acquire (load)Later reads see what the matching release publishedConsuming a flag or pointer
seq_cst (default)Acquire/release plus one total order of seq_cst operationsThe default until a weaker order is justified
A quote has two std::atomic<int> fields, usd and eur, in cents. The feed thread stores both; the status panel loads both. Can the panel show the USD price of one trade with the EUR price of another?

04Practice

Run the quote service

The lab models connection, alerts, currency conversion and drawing with sleeps; it contacts no exchange or rate service. Make startup both defined and non-spinning, compose an indivisible monotonic high update, then keep one quote snapshot across a panel frame. Atomic wait checks its value and can return immediately when it has already changed; notifications make blocked waiters eligible to wake, and notifying alone does not change the value. This one-way startup flag avoids transient-value ABA. Sleeps and the feed-start latch encourage useful overlaps but do not promise wake order, CPU time or a panel frame deadline.

The quote service

One thread per exchange feed reports trade prices to a quote service, which waits for the opening price, keeps the day high and drives a status panel in USD and EUR. Make the service wait correctly, keep the true day high, then stop the panel from mixing two trades.

  1. easy · CPP-ATOMIC-V4-1 Wait for the opening price
  2. medium · CPP-ATOMIC-V4-2 Keep the day high
  3. hard · CPP-ATOMIC-V4-3 Show one trade at a time
Check this idea later
A quote service’s shutdown flag is a plain bool set by a ordinary control thread; the feed loop checks it. Tests pass in debug builds. What is the risk in release builds?
Threads keep the minimum latency in std::atomic<int> best with if (v < best.load()) best.store(v). What is the fix?
One loader writes a config struct’s atomic fields once, then sets atomic<bool> loaded with relaxed. Readers check loaded (relaxed) and load those fields. With no other synchronization, what is wrong?
Sources
In the frontend A complete quote is also a UI invariant Optional

These handlers are under review. The declared convert function asynchronously returns EUR cents at the same fixed 0.92 rate. Both requests succeed; click A then B before either conversion finishes, and let B’s conversion finish before A’s. Which trade supplies each field at the end?

Each state update publishes one object, but that object can still contain fields from different trades. This is logical async interleaving in a UI, not a C++ shared-memory data race. The invariant is the connection: publication must preserve the meaning of the whole value.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';
import { useState } from 'react';

declare function convert(usd: number): Promise<number>;

export default function QuotePanel() {
  const [quote, setQuote] = useState({ usd: 0, eur: 0 });

  async function onQuote(usd: number) {
    setQuote((current) => ({ ...current, usd }));
    const eur = await convert(usd);
    setQuote((current) => ({ ...current, eur }));
  }

  return (
    <>
      <button onClick={() => onQuote(10000)}>Trade A</button>
      <button onClick={() => onQuote(20000)}>Trade B</button>
      <output>{quote.usd} USD cents / {quote.eur} EUR cents</output>
    </>
  );
}

Functional state updaters merge with the current queued value; they do not associate an arriving EUR result with the USD trade that is still displayed. React batching alone does not establish that association.

Sources: React: state as a snapshot,Svelte: state.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.