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.
#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);
}
g++ -std=c++23 -Wall -Wextra -pedantic main.cpp -o main && ./main
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.
| Operation | Indivisible effect | Typical use |
|---|---|---|
| load() / store(v) | Read or write the whole value | Flags, published pointers |
| exchange(v) | Write v and return the old value | Take ownership, reset and read |
| fetch_add(n) | Add n and return the old value | Counters, ticket numbers |
| compare_exchange_weak(e, v) | If the value is e, write v; else copy it into e | Maximum, minimum, any computed update |
| wait(old) / notify_one() | Block while the value equals old; wake a waiter | Waiting without spinning (C++20) |
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.
| Order | Guarantee | Fits |
|---|---|---|
| relaxed | The operation is indivisible; no ordering of other memory | Statistics counters |
| release (store) | Earlier writes become visible to an acquire load that reads this value | Publishing a flag or pointer |
| acquire (load) | Later reads see what the matching release published | Consuming a flag or pointer |
| seq_cst (default) | Acquire/release plus one total order of seq_cst operations | The default until a weaker order is justified |
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.
Check this idea later
Sources
- C++ draft: data races
- C++ draft: atomic operations and compare-exchange
- C++ draft: waiting and notifying
- C++ draft: ordering and consistency
- C++ draft: atomic shared_ptr
- cppreference: Multi-threaded executions and data races
- cppreference: std::memory_order
- cppreference: std::atomic<T>::compare_exchange_weak
- cppreference: std::atomic<T>::wait
- cppreference: std::atomic<std::shared_ptr>
- GCC: Common function attributes (optimize)
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.
'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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?