Memory barrier

Also known as: memory fence

On this page 7

A memory barrier, also called a memory fence, is an instruction that restricts the reordering of memory operations by the compiler or the processor, so that loads and stores issued before the barrier become visible to other threads before those issued after it. In concurrency and low-level programming, memory barriers are the primitive that makes shared-memory communication between threads predictable on hardware that otherwise executes and publishes memory accesses out of program order.

Developers rarely write raw fences in application code. Instead, barriers are emitted implicitly by mutexes, atomic operations and language memory models, but understanding them is essential for lock-free programming, device drivers and diagnosing subtle race conditions.

Why processors and compilers reorder memory operations

Modern hardware reorders memory accesses because strict program order is slow. A processor core places stores in a store buffer so it can continue executing without waiting for the cache, speculatively executes loads early, and may complete independent operations out of order. Compilers perform similar transformations, hoisting loads out of loops or merging writes, as long as the result is correct for a single thread.

These optimizations are invisible to single-threaded code but become visible when another core observes shared memory. A classic failure is the message-passing pattern: one thread writes data and then sets a ready flag, yet a second thread sees the flag set while still reading stale data. A memory barrier between the two writes, paired with one between the two reads, prevents this outcome.

The table below shows the four basic kinds of reordering and which barrier type forbids each.

ReorderingExamplePreventing barrier
Load-loadA later read completes before an earlier readRead barrier or acquire
Store-storeA later write becomes visible before an earlier writeWrite barrier or release
Load-storeA later write becomes visible before an earlier read completesAcquire or release
Store-loadA later read completes before an earlier write is visibleFull barrier only
Memory reordering types and the barriers that prevent them

Types of memory barriers

Memory barriers differ in which directions of reordering they block. A full barrier orders all loads and stores in both directions and is the most expensive. Lighter barriers block only some combinations, which is enough for most synchronization patterns and costs fewer cycles.

Modern language memory models express barriers as ordering semantics on atomic operations rather than as standalone instructions. An acquire operation prevents later accesses from moving before it, while a release operation prevents earlier accesses from moving after it. Pairing a release store with an acquire load on the same variable creates a happens-before relationship between threads.

Barrier kindGuaranteeTypical use
Compiler barrierStops compiler reordering onlyInterrupt handlers, signal-safe code
AcquireNo later access moves before itLock acquisition, reading a ready flag
ReleaseNo earlier access moves after itLock release, publishing data
Full fenceOrders all loads and storesStore-load ordering, Dekker-style algorithms
Sequentially consistentSingle global order of all such operationsDefault atomics in C++ and Java volatile
Barrier kinds and their guarantees

Memory barriers across hardware architectures

How often barriers are needed depends on the hardware memory model. x86-64 uses a strong model called total store order, where only store-load reordering is visible, so most acquire and release operations compile to ordinary moves. ARM, POWER and RISC-V use weakly ordered models that permit almost every reordering, so barriers are emitted far more often.

ArchitectureMemory modelFull barrierLighter options
x86-64Total store orderMFENCE or locked instructionPlain loads and stores for acquire and release
ARMv8 (AArch64)Weakly orderedDMB ISHLDAR and STLR instructions
POWERWeakly orderedsynclwsync for most orderings
RISC-VRVWMO, weakly orderedfence rw,rwAnnotated aq and rl atomics
Barrier instructions on common architectures

This difference explains a common trap: code with a missing barrier may run correctly for years on x86 servers and then fail intermittently on ARM, for example after migrating to ARM-based cloud instances or mobile devices.

Memory barriers in language memory models

High-level languages hide hardware differences behind a portable memory model. C and C++ since the 2011 standards expose memory_order_acquire, memory_order_release, memory_order_seq_cst and related options, plus std::atomic_thread_fence for standalone fences. Java guarantees ordering through volatile fields, synchronized blocks and the VarHandle API. Rust follows the C++ model through std::sync::atomic::Ordering.

The compiler translates these orderings into the cheapest correct instruction sequence for each target. Writing portable code against the language model, rather than inserting architecture-specific fences, is therefore the recommended practice for nearly all software outside kernels and runtime libraries.

Costs, limitations and common mistakes

A full barrier typically costs tens to over a hundred cycles, because the core must drain its store buffer and wait for cache coherence traffic. The exact cost varies with architecture, contention and the number of pending stores, so performance claims should be measured on the target hardware.

A barrier also has clear limits: it orders operations but does not make them atomic, and it does not by itself prevent two threads from modifying the same data. Barriers work only in matched pairs between the writing and the reading thread.

MistakeSymptomFix
Barrier only on the writer sideReader still sees stale dataPair release with acquire
Using volatile in C or C++ for threadsWorks on x86, fails on ARMUse std::atomic with explicit ordering
Relaxed atomics for a ready flagData published before it is writtenUse release store and acquire load
Fences inside hot loopsSevere throughput lossBatch work or use acquire and release
Frequent barrier mistakes

Understanding it simply

Think of a busy office where staff sort mail in whatever order is fastest. Usually that is fine, but sometimes a letter must arrive before a second one that refers to it. A memory barrier is a rule that says nothing behind this line may overtake anything in front of it.

Computers rearrange their work to run faster, and when several workers share the same notes, that shuffling can cause confusion. Barriers restore the expected order exactly where it matters and leave the rest of the work free to run quickly.

Applied in practice

A team maintains a high-frequency logging library in C++ that uses a lock-free ring buffer. A producer thread writes a log record into a slot and then advances a write index; a consumer thread reads the index and then the record. The original code used relaxed atomics for the index and passed every test on x86 servers.

After the company moved its services to ARM-based cloud instances, roughly one record in several million appeared partially written or garbled. Engineers changed the index update to a release store and the consumer read to an acquire load. The corruption disappeared, and measured throughput dropped by less than two percent, far less than a mutex-based design would have cost.