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/acquire

What this lesson walks through

  1. 01Publish data, then set a flag
  2. 02T1 writes data = 42
  3. 03T1: flag.store(true, release)
  4. 04synchronizes-with → happens-before
  5. 05T2: flag.load(acquire) sees true
  6. 06T2 reads data → 42 (guaranteed)
  7. 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.

← Previous
Concurrency: condition_variable — Wait Loop Pattern, Spurious Wakeup, notify_one vs all
Next →
Concurrency: Memory Ordering — relaxed, acquire/release, seq_cst Explained