Course contentsShow
← Computer Science
Lesson 2569 of 2,87257. Concurrency FundamentalsFree lesson

Memory Ordering and Happens-Before

Learning about memory models, sequential consistency, acquire-release semantics, and happens-before relationships.

Memory Ordering and Happens-Before

You'll learn how modern CPUs reorder memory operations and why happens-before guarantees are critical for reasoning about concurrent code.

The Memory Reordering Problem

Modern processors and compilers optimize code aggressively, including reordering memory reads and writes for performance. Two threads might see operations happen in different orders than you wrote them. Imagine you write:

x = 42;
ready = true;

Another thread checking if (ready) might see ready == true but still read the old value of x! The CPU or compiler may have reordered these writes.

Memory Models Define the Rules

A memory model specifies which reorderings are allowed. The strictest model is sequential consistency: all operations appear to execute in program order, as if on a single processor. This is intuitive but expensive.

Weaker models like acquire-release semantics allow more reordering while preserving specific guarantees: an acquire read sees all writes before the corresponding release write. Think of it as a one-way gate: memory operations don't cross certain boundaries.

Happens-Before: Your Reasoning Tool

The happens-before relationship lets you reason about visibility in concurrent systems without understanding every CPU quirk. If operation A happens-before operation B, then A's effects are guaranteed visible to B. Examples:

  • Actions within a single thread happen-before later actions
  • Releasing a lock happens-before acquiring that same lock
  • Writing to a volatile variable happens-before reading it

These rules chain: if A happens-before B and B happens-before C, then A happens-before C.

Key Takeaway: Memory ordering determines which operation reorderings are allowed; happens-before relationships give you concrete guarantees about when one thread's actions become visible to another, enabling correct lock-free and concurrent algorithms.