Memory Barrier

Memory Barrier / Fence — a CPU instruction that enforces ordering of memory operations, preventing the hardware from reordering reads and writes in ways that break concurrent algorithms.

The Problem

  • Modern CPUs and compilers reorder instructions for performance
  • In single-threaded code, this is invisible (correct behavior preserved)
  • In multi-threaded code, reordering can make shared data appear inconsistent to other threads

Example

// Thread 1:               // Thread 2:
data = 42;                 while (!ready) {}  // spin
ready = true;              print(data);      // might print 0!

Without a memory barrier, Thread 1's writes might be reordered or not visible to Thread 2.

Types of Barriers

  • Store Barrier (sfence): All preceding stores complete before later stores
  • Load Barrier (lfence): All preceding loads complete before later loads
  • Full Barrier (mfence): All preceding loads AND stores complete before any later memory operations

Memory Models

  • x86 (TSO): Total Store Order — relatively strong, most programs "just work"
  • ARM/RISC-V: Relaxed ordering — explicit barriers needed more often
  • C++ memory_order: `relaxed`, `acquire`, `release`, `seq_cst` (increasing strictness)

Memory barriers are foundational to lock-free programming and are what make atomic operations correct across cores.

Take memory barrier further

Ask the copilot about this term, or have our engineers assess it against your process.