C++ - Memory Model & Atomics (Deep Dive)

Overview

Estimated time: 80–100 minutes

Understand the C++ memory model: data races, happens-before, atomic orderings (relaxed, acquire/release, seq_cst), and fences.

Learning Objectives

  • Choose appropriate atomic memory order for correctness and performance.
  • Use fences and establish happens-before relationships.

Prerequisites

Atomic ordering

#include <atomic>
std::atomic<int> flag{0};
std::atomic<int> data{0};
// writer
data.store(42, std::memory_order_relaxed);
flag.store(1, std::memory_order_release);
// reader
if (flag.load(std::memory_order_acquire)) {
  int x = data.load(std::memory_order_relaxed);
}

Common Pitfalls

  • Using relaxed everywhere can break ordering; use release/acquire pairs.
  • Forgetting that non-atomic shared writes are data races (UB).