multithreading · advanced
Atomics & Memory Ordering (acquire/release)
Message passing with atomics: a release store synchronizes-with an acquire load to publish prior writes; relaxed ordering would be a data race.
🔑 Key line
release/acquire creates happens-before: writes before a release are visible after an acquire that observes it; relaxed gives no such guarantee.
The code
std::atomic<bool> flag{false};int data = 0;
// Thread 1 (producer)data = 42;flag.store(true, std::memory_order_release);
// Thread 2 (consumer)while (!flag.load(std::memory_order_acquire)) {}assert(data == 42); // guaranteed by release/acquireWhat this lesson walks through
- 01Publish data, then set a flag
- 02T1 writes data = 42
- 03T1: flag.store(true, release)
- 04synchronizes-with → happens-before
- 05T2: flag.load(acquire) sees true
- 06T2 reads data → 42 (guaranteed)
- 07With relaxed: a data race
Thread 1 writes data then sets a flag; Thread 2 spins until it sees the flag, then reads data. The question: is T2 guaranteed to see data = 42?
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Atomics & Memory Ordering (acquire/release) and 100+ animated C++ interview lessons.