arthrop0d

Brief articles on varied topics.

CPU Memory Barriers and Memory Ordering

concurrencycomputer science

A memory barrier is an instruction or compiler constraint that limits how memory operations can be reordered. Memory ordering rules are the guarantees a language and CPU provide about when one thread’s reads and writes become observable to another. Together, they let one thread publish data safely without assuming every core sees memory operations in source-code order.

The problem: source order is not observation order

Consider a producer preparing a message and then setting a flag:

message = "ready";
ready = true;

A consumer might do this:

if (ready) {
    use(message);
}

The intended meaning is clear: if the consumer sees ready == true, it should also see the prepared message. But several layers can break that assumption.

The compiler may reorder instructions when it can preserve the behavior of a single-threaded program. The CPU may also execute or make stores visible in a different order. Each core can have store buffers and caches, and cache-coherence protocols ensure that copies eventually agree without necessarily making every write immediately visible everywhere.

So the consumer could observe the flag as true before it observes the message. Worse, in languages such as C++, an unsynchronized read and write of ordinary shared data can constitute a data race—a conflicting access from different threads without the required synchronization. A data race is not merely “perhaps stale data”; it gives the language permission to behave unpredictably.

A barrier is not primarily a command to flush every cache. It establishes ordering constraints between operations and, when paired with the right operations in another thread, a visibility guarantee.

Publication with release and acquire

The usual pattern is publication: one thread writes an object, then performs a release operation on a shared atomic variable; another thread performs an acquire operation on that variable before reading the object.

In C++, the flag can be atomic and carry those rules explicitly:

#include <atomic>
#include <string>

std::string message;
std::atomic<bool> ready{false};

// Producer
message = "ready";
ready.store(true, std::memory_order_release);

// Consumer
if (ready.load(std::memory_order_acquire)) {
    use(message);
}

An atomic operation is indivisible with respect to other operations on the same atomic object and participates in the language’s synchronization rules. release says: do not allow earlier ordinary writes in this thread to be reordered after this store for the purposes of publication. acquire says: do not allow later reads in this thread to be moved before this load.

If the acquire load reads the value written by the release store—or an appropriately later value in the same atomic’s modification history—the release synchronizes with the acquire. That relationship means the producer’s earlier write to message happens-before the consumer’s later read. “Happens-before” is a language-level ordering guarantee: the read is permitted to rely on the preceding write, rather than racing with it.

The flag is therefore more than a notification. It is the handoff point that carries the ordering guarantee. The consumer must not read message before a successful acquire of ready, and the producer must finish writing it before the release store.

What a barrier does at the hardware level

A compiler must emit code that respects the language’s ordering promise. Depending on the target CPU, this may require a memory fence—a CPU instruction that prevents certain loads or stores from passing one another—or it may be possible to use an already-ordered atomic instruction.

CPUs differ in their default ordering. Some provide relatively strong ordering for ordinary loads and stores; others allow more combinations of loads and stores to become visible out of order. A release store and acquire load may therefore compile to different instructions on different architectures. This is why code that appears to work on one developer laptop can fail on another architecture or under a different compiler optimization level.

A barrier constrains order; it does not make an operation atomic. A non-atomic increment can still lose updates even if surrounded by fences, and a barrier cannot make a compound operation such as “check then modify” indivisible. Use an atomic read-modify-write operation or a lock when the operation itself needs atomicity.

Other ordering strengths

Release and acquire are targeted tools:

A mutex provides a familiar form of the same essential relationship: unlocking after updating data acts as a release, and locking before reading it acts as an acquire. This is why replacing a lock with a plain Boolean flag is not a safe optimization.

Common mistakes

volatile is not a substitute for synchronization in C++. It can affect compiler treatment of accesses, but it does not generally provide atomicity or establish inter-thread happens-before relationships. Similarly, inserting a fence in only one thread is not automatically enough: the other thread needs a matching atomic operation or synchronization mechanism that connects the two sides.

Finally, publication is safe only while the published object is not concurrently modified without further synchronization. After publishing an immutable message, many consumers can read it. If a producer later changes that message while consumers read it, those later accesses need their own synchronization.

The terms release, acquire, fence, and reordering in concurrency bugs, compiler flags, and architecture-porting notes usually point to this same issue: program order is local to a thread, while safe communication requires an explicit ordering relationship between threads.

← All articles