Lesson 5 of 9 · 26m
Atomics and Memory Ordering
What atomic operations guarantee, how compare-and-exchange works, and how to choose between relaxed, acquire/release, and sequentially consistent ordering without fooling yourself.
Atomics seduce experienced engineers because the operations look small and precise. Increment one integer, compare one pointer, avoid a lock. The trap is that atomicity and ordering are separate guarantees. An atomic operation cannot be torn — nobody observes half a write — but without the right memory ordering it does not publish other writes or prevent surprising reordering.
Atomic means indivisible, not coordinated
std::atomic<int> counter{0};
void worker() {
for (int i = 0; i < 100000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}This counter is correct if the only thing you need is the final count. Every increment is atomic and the additions do not get lost. The relaxed ordering is enough because the counter does not publish other data. If the counter were a completion flag guarding initialized state, relaxed would be wrong.
Compare-and-exchange builds higher-level operations
Compare-and-exchange, usually abbreviated CAS, performs "if the current value is still X, replace it with Y" in one atomic operation:
std::atomic<int> best{0};
void observe(int score) {
int current = best.load(std::memory_order_relaxed);
while (current < score &&
!best.compare_exchange_weak(current, score,
std::memory_order_relaxed)) {
// compare_exchange_weak updates `current` on failure
}
}The loop is the pattern: read, compute a candidate, install only if nobody else changed the value. Retrying is normal. If you write CAS code without expecting contention and retry, you have misunderstood the primitive.
The orderings you actually need
C++ exposes several orderings, but three cover most practical work:
memory_order_relaxed— atomicity only; useful for counters, statistics, and values that do not publish other statememory_order_release/memory_order_acquire— a one-way publish/subscribe pair; writes before release become visible after the matching acquirememory_order_seq_cst— the default; atomic plus a single global order for seq_cst operations Sequentially consistent is the easiest to reason about and often the right starting point. Optimize to acquire/release or relaxed only when profiling says the synchronization cost matters and you can explain the required ordering in one sentence.
False sharing can dominate the real cost
Even correct atomics can destroy performance when unrelated counters sit on the same cache line. CPU cores invalidate the whole line, not the individual field, so two threads incrementing adjacent counters can bounce the line between caches.
struct alignas(64) Counter {
std::atomic<long> value{0};
};
Counter counters[worker_count]; // each counter owns a cache lineIf throughput mysteriously collapses as worker count grows, look for cache-line contention before rewriting the algorithm. Linux perf stat -e cache-misses and perf c2c can expose this class of problem.
Field notes
- Use
compare_exchange_weakinside retry loops; spurious failure is legal and cheaper on some architectures. - Atomicity of one object says nothing about consistency across two objects. Multi-field invariants still need a lock or a carefully published immutable snapshot.
- Acquiring a lock normally gives you acquire/release semantics already. Do not duplicate ordering with atomics unless the design genuinely requires it.
- Memory-ordering bugs are architecture-sensitive. x86 can hide mistakes that ARM exposes quickly.
- A comment that says "relaxed is safe here because..." is documentation. If you cannot write that sentence, use the stronger ordering.
Was this lesson helpful?