Advanced · Module 12
Atomics and the Memory Model
Count and flag without locks using atomics, understand what the memory model promises, and verify with sanitizers.
A mutex around a counter works but serializes every increment. Atomics let the hardware do it: one indivisible fetch_add, no lock, no context switch. This module fixes the example race as the motivating bug, uses the example to compare mutex versus atomic versus semaphore, and closes with ThreadSanitizer and unit tests for the thread-pool project.
- 1Data Races: The Bug Locks PreventPro — members onlySee why unsynchronized shared increments are undefined behavior, fix the even-odd race with an atomic, and know when a mutex still wins.10 min
- 2std::atomic: Counters and Flags Without MutexesPro — members onlyReplace lock-guarded increments with indivisible fetch operations, compare throughput against mutexes, and signal state with atomic flags.10 min
- 3Acquire-Release: Publishing Work SafelyPro — members onlyPublish data with release stores and acquire loads so readers observe complete work, and bound concurrency with a three-permit semaphore.11 min
- 4Sanitizers and Tests: Proving the Pool CorrectPro — members onlyCompile with address, thread and undefined sanitizers, then assert single execution, queue draining and clean shutdown for a small pool.12 min
- 5Atomic Waiting, Notification and atomic_refPro — members onlyReplace polling loops with atomic wait and notify, and understand when atomic_ref can retrofit atomic access to existing storage.11 min