arthrop0d

Brief articles on varied topics.

Memory Barriers and Safe Producer-Consumer Handoffs

operating systemsconcurrency

A memory barrier is an instruction or language-level operation that constrains the order in which memory accesses become visible to other threads. It prevents selected loads and stores from being reordered across a boundary, allowing one thread to publish data and another to consume it safely.

The problem: source order is not observation order

Consider a producer that fills in a value and then raises a flag:

message = 42;
ready = true;

A consumer waits for the flag and then reads the value:

while (!ready) {
    // wait
}

use(message);

The intended meaning is obvious: if the consumer sees ready == true, it should also see message == 42. Without synchronization, that conclusion is not guaranteed on a multicore system.

There are two separate reasons.

First, the compiler may rearrange operations when it believes the change cannot affect a single-threaded program. Second, the processor may execute or make operations visible in a different order from the source code. A core can place a store in a store buffer, a temporary queue holding writes before they reach the cache-coherent memory system. Another core may observe a later store before the earlier one has become visible to it.

A cache-coherent system eventually works to give cores compatible values for each memory location, but coherence does not by itself preserve the order of writes to different locations. The consumer might therefore observe ready == true while still seeing the old value of message.

A barrier is about ordering observations, not about making every operation instantly visible everywhere.

Loads can also be observed or executed early. Modern processors predict branches and perform speculative execution, meaning they tentatively run instructions before it is certain that those instructions are needed. They can later discard the results, but the memory-ordering rules still determine what values a program is allowed to use. These optimizations are normally invisible; unsynchronized communication between threads is where their effects become a correctness bug.

What a barrier orders

A barrier divides memory operations into those before it and those after it. Its exact guarantees depend on its kind, but the usual promise is that selected operations cannot cross that boundary in the relevant direction.

For example:

These names describe ordering constraints, not necessarily a request to flush every cache line. The processor may satisfy a barrier by delaying execution, draining a store buffer, or using the coherence protocol to ensure that other cores cannot observe the forbidden order.

A language or library may expose barriers at a higher level. In C++, for example, atomic operations can carry memory-ordering semantics: rules that constrain both compiler transformations and processor behavior. This matters because a hardware fence alone does not stop the compiler from moving ordinary code around it, and a compiler-only rule cannot repair a processor-level ordering problem.

Release and acquire: the handoff pattern

The most useful producer-consumer pattern uses a release operation to publish data and an acquire operation to receive that publication.

A release prevents earlier memory operations in that thread from being reordered after the publication. An acquire prevents later memory operations in that thread from being reordered before the observation. When an acquire reads the value written by a matching release operation on the same atomic variable, the language memory model creates a happens-before relationship: the consumer is guaranteed to see the producer's earlier writes.

In C++, the handoff can look like this:

#include <atomic>

int message = 0;
std::atomic<bool> ready{false};

void producer() {
    message = 42;
    ready.store(true, std::memory_order_release);
}

void consumer() {
    while (!ready.load(std::memory_order_acquire)) {
        // wait
    }

    use(message); // guaranteed to observe the producer's prior write
}

ready is atomic, so concurrent access to it follows defined rules. The release store publishes the write to message; the acquire load that observes true consumes that publication. The data can then be an ordinary variable because the synchronization prevents the producer's write and consumer's read from racing.

The acquire must actually observe the release, directly or through the defined atomic modification order. Merely using acquire on one unrelated variable and release on another does not create this handoff.

What barriers do not do

A barrier is not a lock. It does not make a sequence indivisible, prevent two threads from entering a critical section, or automatically make every shared variable safe. It orders memory operations; mutual exclusion requires a mutex or another suitable coordination mechanism.

Nor does adding a barrier after a data race necessarily fix a program. The synchronization must be connected to the communication: the producer must publish through an atomic operation, and the consumer must acquire through the corresponding observation. In C++, using non-atomic data concurrently without such a relationship is still a data race, even on hardware where tests appear to work.

The strongest commonly used C++ ordering, std::memory_order_seq_cst, adds a single global order for sequentially consistent atomic operations. It is easier to reason about but can impose more constraints than a release-acquire handoff needs. Release and acquire express the actual producer-consumer relationship directly.

Where this appears in practice

This is the mechanism behind many queue implementations, worker handoffs, readiness flags, and “published configuration” bugs. It also explains why a failure may disappear on one machine and recur on another: x86 processors usually provide stronger ordering than architectures such as ARM, while the compiler remains free to optimize unless the program uses a language-level synchronization primitive.

When an incident report says a thread saw a flag but stale data, the missing piece is usually not cache invalidation in the everyday sense. It is an absent ordering relationship. A release operation publishes the preceding work; an acquire operation makes that publication usable by the receiving thread.

← All articles