Memory Models and Visibility

Topics Covered

Why Memory Is Not Sequential

Sequential consistency

Compiler reordering

Processor reordering and store buffers

Why the reordering is worth it

Litmus tests

Speculation and out of order loads

When you read a program, you naturally imagine that each statement takes effect in order, and that every thread looks at the same single memory in which writes appear the moment they happen. That mental model, called sequential consistency, is what most people mean when they reason about interleavings. Real machines do not work that way. Compilers reorder and eliminate memory accesses, and processors buffer, reorder and speculate on them, because doing so makes single threaded code dramatically faster. A memory model is the contract that says which of those reorderings another thread is allowed to observe. This section explains where the reorderings come from and why they exist.

Sequential consistency

Leslie Lamport defined sequential consistency in 1979: the result of any execution is the same as if the operations of all processors were executed in some single sequential order, and the operations of each individual processor appear in this sequence in the order specified by its program. In other words, the execution is some interleaving of the threads, with each thread kept in program order. Under sequential consistency, the only concurrency bugs are atomicity bugs; there are no surprises about visibility or ordering, because every write is instantly visible to everyone in one global order.

Sequential consistency is easy to reason about and expensive to implement. It would forbid almost every optimization that compilers and processors use to hide the latency of memory, which is roughly a hundred times slower than an arithmetic operation. No mainstream processor provides it for ordinary loads and stores, and no mainstream language compiler provides it for ordinary variables. Instead, languages provide it for programs that are free of data races, which is the bargain this lesson explains.

Compiler reordering

Compilers transform code aggressively as long as a single thread cannot tell the difference. They keep variables in registers instead of reloading them from memory, move loads earlier to hide their latency, sink stores later, merge adjacent stores, remove stores that are overwritten before being read, and hoist loop invariant loads out of loops. All of these are correct for a single thread. Each of them can break a program in which another thread is reading or writing the same variables without synchronization.

The flag loop from the previous lesson is the canonical example: the compiler sees that nothing in the loop body writes the flag, so it reads it once before the loop. Another example: a thread writes data, then writes ready = true. The compiler may swap those two stores, since they are to different addresses and the thread itself reads neither, so another thread can observe ready before data. Volatile in C and C++ prevents some of these transformations for one variable but provides no ordering with other variables and no atomicity, which is why it is not a synchronization tool in those languages.

To a single thread, the order of two stores to different variables does not matter, so the compiler may swap them. Another thread can see the difference.

Processor reordering and store buffers

Even when the compiler emits instructions in source order, the processor may make their effects visible to other cores in a different order. The most important reason is the store buffer. When a core executes a store, it does not wait for the cache line to arrive in its cache in a writable state, which can take hundreds of cycles if another core owns it. It places the store in a small private queue, the store buffer, and keeps executing. The store becomes visible to other cores only when it drains from the buffer into the cache. Meanwhile, the core that made the store sees its own value through store forwarding, so a single thread never notices.

The consequence is that a store followed by a load to a different address can appear reordered to other cores: the load reads from the cache while the earlier store is still sitting in the buffer. On x86, this store to load reordering is the only reordering the hardware allows for ordinary accesses, a model called total store order, TSO. ARM and POWER processors allow much more: stores can become visible out of order with each other, loads can be satisfied out of order, and different cores can see stores from other cores in different orders. Code that happens to work on an x86 laptop can fail on an ARM server or a phone.

Each core parks its store in a private buffer and reads the other variable from cache before the buffer drains. Both read 0.

Why the reordering is worth it

It is tempting to view all this as a defect, but the performance stakes are large. A store that misses in cache would stall a core for hundreds of cycles without a store buffer. Out of order execution lets a core keep dozens of memory operations in flight, hiding latency that would otherwise dominate run time. Compiler optimizations such as register allocation and loop invariant code motion speed up typical code by integer factors. Requiring sequential consistency for every access would throw most of this away, slowing ordinary single threaded code, which is the vast majority of code, to protect the minority of accesses that are actually shared.

The solution chosen by every mainstream language is to keep the fast, reorderable behavior for ordinary accesses, and to give programmers explicit tools, locks and atomics with specified orderings, to mark the accesses that communicate between threads. Those tools compile to special instructions, fences or ordered loads and stores, that restrict reordering only where it matters.

Litmus tests

Memory model behavior is usually described with litmus tests: tiny multithreaded programs with a question about which final results are possible. The store buffer example is the test called SB: thread 0 writes x and reads y, thread 1 writes y and reads x; can both reads return 0? Under sequential consistency no, on x86 yes, on ARM yes. The message passing test, MP: thread 0 writes data then flag, thread 1 reads flag then data; can thread 1 see the flag set but old data? On x86 no, on ARM yes, unless barriers are used. Tools such as herd7 and the litmus testing suite from the Cambridge and Inria researchers run thousands of such tests against formal models and real hardware, and they are how hardware vendors and language designers check that their memory models are consistent.

Speculation and out of order loads

Modern cores also execute loads out of order and speculatively. A core that reaches a load whose address is known may issue it before earlier loads complete, and even before it knows whether a branch leading to it will be taken. If the speculation turns out to be wrong, the core discards the results, but for ordinary loads on weak architectures, the value may simply have been read earlier than program order suggests. x86 hides this by replaying loads if the line they read was invalidated before they retire, which is how it keeps load to load order. ARM does not promise that order for independent loads, so a reader that loads a flag and then data may effectively read the data first. That is why the reader side of message passing needs acquire ordering on weak hardware, not only the writer side.

The overall lesson is that ordering is a contract between two threads. A release on the writer is useless without an acquire on the reader, and vice versa. Both halves must be present for the guarantee to hold.

Assume reordering unless you synchronized

Sequential consistency is the model people imagine, but compilers reorder and cache variables in registers, and processors use store buffers and out of order execution so that other cores see writes late and out of order. x86 allows only store to load reordering, while ARM and POWER allow much more. Locks and atomics with explicit ordering are how programs mark the accesses that must not be reordered.