Two separate questions
An atomic operation answers two questions that are easy to blur together:
- Atomicity. Is the operation indivisible? An atomic
fetch_addcan never lose an update, and an atomic load never sees half of a store. - Ordering. What does this operation tell me about other memory, the plain variables around it? This is what
std::memory_ordercontrols.
Atomicity is always guaranteed by std::atomic<T>. Ordering is the part that is subtle, because both compilers and CPUs reorder memory accesses. A store can sit in a core's store buffer while later loads run ahead; ARM and POWER reorder far more than x86. Single-threaded code cannot tell, but another core can.
The toolkit
std::atomic<T> works for integers, pointers, bool and any trivially copyable T; check is_lock_free() (or is_always_lock_free), because a large T may fall back to a hidden lock.
| Operation | Meaning |
|---|---|
load, store | Read or write atomically. |
exchange(v) | Write v, return the old value, as one step. |
fetch_add, fetch_sub, fetch_or, ... | Read-modify-write (RMW) in one step; returns the old value. |
compare_exchange_weak/strong(expected, desired) | CAS: if the value equals expected, write desired and return true; otherwise copy the current value into expected and return false. |
compare_exchange_weak may fail spuriously (it maps to load-linked/store-conditional on ARM), so use it inside a retry loop; use strong when a single attempt must be decisive.
An RMW on a contended cache line is expensive: the line has to move to the writing core in exclusive state each time, so a counter hammered by many cores costs on the order of 100 ns per increment however cheap the instruction looks.
The three orderings you need
memory_order_relaxed: atomicity only. Every atomic variable still has a single modification order that all threads agree on, but relaxed operations impose no ordering on any other variable. Correct for statistics counters, sequence-number generators where nothing else is published, and the thread's own index in the queue of the next lesson.
memory_order_release (on a store) / memory_order_acquire (on a load): if an acquire load reads the value written by a release store, the store synchronises with the load. Then everything the writer did before the release happens before everything the reader does after the acquire. Picture the release as "flush everything I wrote before this point" and the acquire as "do not let anything after this point start early". acq_rel is both, for RMWs.
memory_order_seq_cst (the default): acquire/release, plus all seq_cst operations appear in one total order that every thread agrees on. This is the only ordering that forbids the "store buffering" outcome below.
Approximate costs: on x86, plain loads and stores already have acquire/release semantics, so those orderings are free at the instruction level, while a seq_cst store becomes xchg (a full barrier, roughly 20 cycles or more). On ARM64, acquire/release map to ldapr/ldar and stlr, which are cheap; relaxed is plain ldr/str. In all cases the bigger cost of a stronger order is often the optimisations it prevents.
Happens-before, step by step
#include <atomic>
#include <cassert>
#include <iostream>
#include <thread>
struct Quote { double bid, ask; };
Quote snapshot; // plain, non-atomic data
std::atomic<bool> ready{false}; // the flag that publishes it
int main() {
std::thread writer([] {
snapshot = {99.5, 100.5}; // (1) plain writes
ready.store(true, std::memory_order_release); // (2) publish
});
std::thread reader([] {
while (!ready.load(std::memory_order_acquire)) // (3) wait for the flag
; // spin
assert(snapshot.bid == 99.5 && snapshot.ask == 100.5); // (4) guaranteed
std::cout << "bid " << snapshot.bid << " ask " << snapshot.ask << '\n';
});
writer.join();
reader.join();
}
Output: bid 99.5 ask 100.5. The chain is: (1) is sequenced before (2) in the writer; (2) synchronises with the load at (3) that reads true; (3) is sequenced before (4). So (1) happens before (4), and the reader is guaranteed to see the full quote, with no data race on snapshot even though it is not atomic. If (2) were relaxed, the flag could become visible before the quote and (4) would be a data race.
Note what this does not do: the writer may not modify snapshot again while the reader might be reading it. Publishing once is safe; repeated publishing needs a protocol (a seqlock, double buffering, or a queue).
Worked example
where acquire/release is not enough
Two threads start with x = y = 0 (both atomic). Thread A runs x.store(1); r1 = y.load(); and thread B runs y.store(1); r2 = x.load();. Can the program end with ? Answer for release stores with acquire loads, then for seq_cst, and test it.
Show solutionHide solution
Reasoning. With release/acquire, synchronisation only arises when an acquire load reads a value written by a release store. Here, if both loads read 0, neither reads the other's store, so no happens-before edge exists and nothing forbids the outcome. In hardware terms, each store can wait in its core's store buffer while the following load reads the old value from cache. Release orders earlier accesses before the store and acquire orders later accesses after the load, but neither stops a later load from overtaking an earlier store.
With seq_cst, all four operations sit in one total order. Whichever store comes first in that order precedes the other thread's load, which must therefore read 1. So is impossible.
Test. A litmus harness runs the two-line bodies 200,000 times, resetting and and releasing both threads together each round (the full program is longer than it is interesting; the bodies are exactly as above with the orders as template parameters). On an Apple M1, twice:
release/acquire: 199480 of 200000
seq_cst: 0 of 200000
release/acquire: 199618 of 200000
seq_cst: 0 of 200000
The forbidden-looking outcome happened almost every round with release/acquire and never with seq_cst. This pattern (each thread announces itself, then checks the other) is Dekker-style mutual exclusion and appears in hazard pointers and some shutdown protocols: it needs seq_cst or an explicit std::atomic_thread_fence(std::memory_order_seq_cst) between the store and the load. Message passing (one writer, one reader, one flag) does not, which is why it can use the cheaper orders.
Worked example
a lock-free running maximum with CAS
Four threads each produce one million values; thread produces for . Keep an atomic fill counter and an atomic running maximum without a mutex. What should they read at the end?
Show solutionHide solution
There is no fetch_max in C++20, so use a CAS loop: read the current maximum; while our value is larger, try to swap it in; on failure compare_exchange_weak has reloaded cur, so the loop re-tests against the fresh value and stops as soon as someone else has stored something at least as large. Both variables are standalone statistics that publish no other data, so relaxed is enough.
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main() {
std::atomic<long> fills{0};
std::atomic<long> max_seen{0};
std::vector<std::thread> ts;
for (int t = 0; t < 4; ++t)
ts.emplace_back([&, t] {
for (long i = 0; i < 1'000'000; ++i) {
fills.fetch_add(1, std::memory_order_relaxed); // a counter: relaxed is enough
long v = t * 1'000'000 + i;
long cur = max_seen.load(std::memory_order_relaxed);
// CAS loop: on failure, cur is reloaded with the current value
while (v > cur && !max_seen.compare_exchange_weak(cur, v, std::memory_order_relaxed))
;
}
});
for (auto& th : ts) th.join();
std::cout << "fills = " << fills << ", max = " << max_seen << '\n';
}
Output: fills = 4000000, max = 3999999. The largest value is , and the counter lost nothing. Reading the results in main after join is safe because join synchronises.
The ABA problem
CAS checks that a value is the same, not that nothing happened. Consider a lock-free stack (Treiber stack) whose pop is
Node* old = top.load();
while (old && !top.compare_exchange_weak(old, old->next)) {}
- Thread 1 reads
top = AandA->next = B, then is pre-empted. - Thread 2 pops A, pops B (and frees B), then pushes A back.
topis A again. - Thread 1 resumes. Its CAS sees
top == Aand succeeds, settingtop = B: a pointer to freed memory.
The value went A, then B, then A again, and CAS cannot tell. Remedies:
- Tagged pointers / version counters. Store a counter next to the pointer and increment it on every change, CASing both together (a 16-byte CAS such as
cmpxchg16b, or spare high bits of the pointer). A recycled A then has a different tag. - Safe memory reclamation. Hazard pointers or epoch-based reclamation guarantee a node is not freed or reused while any thread might still dereference it.
- Avoid the shape. Index-based ring buffers that only ever move forward (next lesson) do not have the problem, which is one reason trading systems prefer them.
Knowledge check
In the message-passing example, the writer's ready.store is changed to memory_order_relaxed and the reader's load stays acquire. What happens?
Knowledge check
Several threads count processed messages with counter.fetch_add(1); only the final total, read after all threads are joined, matters. Which ordering is appropriate?
Knowledge check
A lock-free stack's pop does CAS(top, old, old->next). Which scenario is the ABA problem?
Key takeaways
- Atomics give atomicity always; the memory order says what other memory is ordered around the operation.
- Release store plus acquire load of the same value creates happens-before: everything before the release is visible after the acquire. That is enough for one-way message passing.
- Only seq_cst forbids store buffering (both threads reading 0 after writing 1). Use it, or a seq_cst fence, for Dekker-style "announce then check" protocols.
- Relaxed is right for counters and statistics that publish nothing else.
- Contended RMWs are expensive because the cache line bounces between cores.
- CAS cannot see ABA; use tags, safe reclamation, or monotonic indices.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).