Skip to content

Lesson 3 of 9 · 28m

Memory Ordering: Where Concurrent Intuition Goes to Die

Learn why cores may observe memory operations out of order, what atomics actually guarantee, and how to reason about flags, publication, and locks.

The worst concurrency bug I ever reviewed passed tests for months because the developer machine's timing hid it. On a different architecture it failed within minutes. The code looked obvious: set data, set a flag, read the flag, use the data. CPUs and compilers are allowed to make that not obvious at all.

Memory ordering is about visibility, not execution order

Each core has its own cache, store buffer, and speculative machinery. Writes do not instantly become globally visible in program order, and reads may move ahead of logically earlier writes. The language memory model defines which reorderings are forbidden for correctly synchronized programs.

// thread 1
payload = 42;
ready = true;

// thread 2
if (ready)
    print(payload);

If both variables are plain non-atomic data, this is a data race in C and C++ and the program has undefined behavior. Even with atomics, the default ordering you choose changes what thread 2 is guaranteed to see.

Atomicity is not ordering

An atomic operation is indivisible, but atomicity alone does not create a happens-before relationship. memory_order_relaxed is useful for counters where no data publication depends on the order. It is not a publication primitive.

std::atomic<int> tickets{0};
tickets.fetch_add(1, std::memory_order_relaxed);  // only the count is atomic

std::atomic<bool> ready{false};
payload.store(42, std::memory_order_relaxed);
ready.store(true, std::memory_order_release);

if (ready.load(std::memory_order_acquire))
    use(payload.load(std::memory_order_relaxed));

Release-store pairs with acquire-load. Together they promise that writes before the release are visible to a thread that observes the flag with acquire.

Strong hardware does not make wrong software correct

x86 is comparatively strongly ordered, while ARM permits more visible reordering. Code can appear stable on one machine and fail on another. Do not infer correctness from a passing test or from the architecture on your laptop. Infer it from the language memory model.

Compiler reordering is real too

Even if the CPU behaved exactly as imagined, compilers can move, merge, or eliminate memory operations when the language says no synchronization exists. This is why handwritten volatile flags are broken: volatile means the access happens, not that it synchronizes with another thread.

Locks are easier because they bundle ordering

A mutex lock generally has acquire semantics; unlock has release semantics. Everything before unlock becomes visible to a thread that subsequently locks the same mutex. Use locks first. Reach for lock-free algorithms only when contention or latency measurements justify their complexity.

The practical rules

plain shared mutable data              -> data race
atomic counter without publication     -> relaxed is often enough
publish data through flag or pointer   -> release/acquire or stronger
multiple objects with global ordering  -> understand seq_cst cost
complex lock-free structure            -> prove invariants, use established libraries

Sequential consistency is the easiest atomic default mentally, but it can impose ordering the algorithm does not need. Optimize ordering only after the algorithm is correct under stronger ordering.

Field notes

  • If two threads access the same object and one writes, atomics or external synchronization are required; intuition is irrelevant.
  • Release/acquire synchronizes through the same atomic object; unrelated atomics do not automatically create the relationship.
  • Test concurrency on multiple architectures when possible. ARM hardware exposes reorderings x86 often hides.
  • A sleep-and-check test is a reproduction aid, not evidence of correctness.

Was this lesson helpful?

Sign in to rate