CPU Cache Coherence: MESI, Snooping, and False Sharing
CPU cache coherence is the set of hardware rules that keeps cached copies of shared memory consistent when several cores execute at the same time. It lets a thread read data that another core has modified without software manually copying every cache line. For developers and systems engineers, it explains both why multicore code can work and why a small layout mistake can make a parallel program slow.
What Is CPU Cache Coherence?
Modern processors do not read every variable directly from DRAM. Each core normally has private, fast caches, while larger cache levels may be shared by several cores. When a core loads a memory location, it usually brings an aligned block called a cache line into its cache. A later access to another byte in that line can be served locally.
If two cores cache the same line, the system has multiple copies of the same memory region. Cache coherence defines how those copies are kept consistent when one core writes. A common rule is that a write obtains exclusive ownership of the line and causes other cached copies to be invalidated or otherwise updated. A later reader must then obtain the current data.
Coherence applies to a particular memory location or cache line. It does not by itself define the order in which independent locations become visible to software. That broader question is memory consistency or memory ordering. The distinction matters because a coherent processor can still allow reordered observations unless the language, atomic operation, lock, or memory barrier supplies the required ordering.
The Intel 64 and IA-32 Architectures Software Developer’s Manuals document the architecture and programming environment for Intel processors, including multiprocessor support.
Why Cache Coherence Exists
Without coherence, each core could continue reading its own stale copy after another core updated shared memory. A producer could set a flag, for example, while a consumer kept seeing the old flag in its local cache indefinitely. Software could avoid the problem by flushing and reloading memory explicitly, but that would make ordinary shared-memory programming difficult and would impose large coordination costs.
Coherence lets hardware coordinate copies close to where they are used. It is especially important for:
- Thread communication: one thread can publish data and signal another through shared memory when the program uses valid synchronization.
- Locks and atomics: mutexes, atomic variables, and operating-system primitives depend on cores observing ownership and updates consistently.
- Operating-system state: scheduler queues, page metadata, and other kernel structures may be accessed by multiple CPUs.
- Parallel algorithms: workers can share queues, counters, and result buffers.
The benefit is not free. A write to a shared line can make other copies unusable, and ownership requests consume bandwidth and latency. More contention makes execution less parallel.
How Cache Coherence Works
A simplified write-invalidate flow looks like this:
- Core A reads a line and obtains a shared copy.
- Core B reads the same line and also obtains a shared copy.
- Core A wants to write, so it requests exclusive ownership.
- The coherence system invalidates Core B’s copy or records that it is no longer valid.
- Core A writes its owned copy and eventually writes it back or supplies it to another requester.
- If Core B reads the line again, it must obtain the current version.
The actual path may involve private L1 and L2 caches, a shared last-level cache, a ring or mesh interconnect, a home agent, and memory controllers. A cache miss is therefore not always a trip to DRAM. Another core’s cache, a shared cache, or a coherence directory may supply the line first.
MESI states
Many coherence protocols describe a cache line with states similar to MESI. Real processors can add transient states and implementation-specific details.
| State | Meaning for the cache line | Can this cache write without asking? |
|---|---|---|
| Modified (M) | This cache has the newest copy, and main memory may be stale | Yes |
| Exclusive (E) | This cache has the only cached copy, matching memory | Usually yes; the line transitions to Modified |
| Shared (S) | Multiple caches may hold the line, and the copy is clean | No; ownership is required first |
| Invalid (I) | This cache must not use its current copy | No; it must fetch or obtain the line again |
When a core reads a clean line that no other cache has, it may receive the Exclusive state. If another core reads it, both can hold Shared copies. A write to a Shared line requires a transition that gives the writer exclusive ownership and invalidates the other copies. A write to an Exclusive line can transition directly to Modified.
Protocols extend this basic model. MOESI adds an Owned state that can let one cache supply dirty data to other readers without immediately writing the data to memory. MESIF adds a Forward state to identify a preferred cache to respond to shared reads. These extensions can reduce traffic or select a more efficient data source; they do not change the programmer’s basic obligation to use correct synchronization.
Snooping and directory-based coherence
There are two broad ways a system can find other copies:
- Snooping: caches monitor a shared broadcast or logically shared request channel. A cache that has the requested line responds or changes its state. Snooping can be simple and fast for smaller systems, but broadcasting every request becomes expensive as the number of agents grows.
- Directory-based coherence: a directory tracks which caches may hold each line. A request is routed to the relevant agents instead of being broadcast to everyone. Directories scale better in many large systems, but they consume storage and add control logic and lookup steps.
Many processors combine techniques. A directory can filter requests at a higher level while local snoop-like actions handle a smaller group of cores. The topology, cache hierarchy, interconnect, line size, and workload determine the cost of a coherence event.
Coherence, Consistency, and Atomicity
These terms are related but not interchangeable:
- Coherence asks whether different caches agree about one memory location or line, especially the order of writes to that location.
- Consistency asks what ordering of operations across one or more locations a program may observe.
- Atomicity asks whether an operation appears indivisible to other observers. A cache line being coherent does not make a compound read-modify-write operation atomic.
- Synchronization supplies the language or operating-system rules that establish visibility and ordering between threads.
For example, two threads incrementing a shared ordinary integer can both read the same old value and then write back the same new value. The line may remain perfectly coherent while one increment is lost. Replacing the variable with a suitable atomic operation or protecting it with a mutex addresses the read-modify-write race; merely relying on cache coherence does not.
The C++ working draft’s data-race and synchronization rules define acquire and release operations, fences, modification order, and the conditions under which conflicting operations form a data race. A C++ compiler is allowed to transform ordinary non-atomic code according to those rules. Hardware coherence cannot make a program with a language-level data race valid.
The Linux kernel memory-barriers documentation makes a similar distinction for kernel code: barriers constrain the ordering that other CPUs can observe, while cache coherency concerns the relationship between cached data and other agents. The document is a guide rather than a complete hardware specification, so kernel code should use the established atomic and locking APIs instead of inventing ad hoc barriers.
False Sharing and Cache-Line Contention
False sharing occurs when independent variables used by different cores occupy the same cache line. The variables are logically unrelated, but the coherence system tracks the line as one unit. A write by Core A invalidates the line in Core B’s cache even when Core B is updating a different variable on that line.
Consider this conceptual layout:
Cache line 0
+----------------------+----------------------+
| counter_for_core_0 | counter_for_core_1 |
+----------------------+----------------------+
If both counters are incremented frequently, ownership can bounce between cores. This is sometimes called cache-line ping-pong. The program may show high CPU usage but make little progress because workers spend time obtaining ownership and waiting for invalidations.
False sharing differs from true sharing. In true sharing, several cores really do need the same data, such as a work queue head or a reference count. Padding those variables may not remove the required communication. In false sharing, separating independent hot variables can reduce unnecessary traffic.
Cache lines also explain why an array of per-thread counters may scale differently from an array of structures. The exact line size and alignment are platform details, so portable code should use the language’s alignment facilities and verify layout rather than assuming a particular value. Padding increases memory use and can make scans less cache-friendly, so it should be applied to measured hot paths, not everywhere.
Real-World Uses and Performance Effects
Coherence is involved in nearly every shared-memory multicore workload:
- Web servers and worker pools: request queues, statistics, connection state, and allocators are shared between threads. A single global counter can become a serialization point.
- Databases: buffer metadata, lock tables, transaction state, and indexes may be accessed by many cores. Partitioning ownership can reduce contention.
- Operating systems: kernel locks and per-CPU data structures balance correctness against cross-CPU communication.
- Scientific and AI workloads: large arrays may be partitioned so workers mostly write disjoint regions. Layout, NUMA placement, and synchronization frequency still affect throughput.
Coherence traffic is only one possible bottleneck. A workload can also be limited by memory bandwidth, remote NUMA access, branch behavior, locks, or insufficient parallel work. NUMA and memory locality in multicore systems explains why the location of a page relative to a CPU matters even when the address space is shared.
Practical Guide: Inspecting and Reducing Coherence Costs
Start with a repeatable workload and a baseline. Measure throughput, latency, CPU migrations, and scaling as worker count increases. A program that stops scaling may be suffering from synchronization or memory traffic rather than a lack of arithmetic capacity.
On Linux, perf can help profile cache behavior. Event names differ by CPU, so list the events supported by the target machine before selecting one:
# See hardware cache and memory events available on this host.
perf list cache
# Record a workload with hardware cache events when supported.
perf stat -e cache-references,cache-misses \
./your-program --threads 8
These generic events are useful starting points but do not directly measure every coherence invalidation. For deeper diagnosis, use processor-specific events, a profiler that reports cache-line contention, or a microbenchmark that varies data layout. Compare the same binary and workload with one, two, and several workers; a large slowdown as workers share a line is evidence worth investigating, not proof by itself.
In C++, an explicitly separated counter can be represented as follows:
#include <atomic>
#include <cstddef>
struct alignas(64) PaddedCounter {
std::atomic<unsigned long long> value{0};
};
PaddedCounter counters[8];
void record(std::size_t worker_id) {
counters[worker_id].value.fetch_add(1, std::memory_order_relaxed);
}
The relaxed ordering is appropriate only when the counter is an independent statistic and does not publish or protect other data. It still provides an atomic read-modify-write for the counter. If a counter also signals that a data structure is ready, use a synchronization design with the required acquire and release semantics instead of copying this example.
Practical ways to reduce unnecessary coherence traffic include:
- Partition writes so each worker owns a separate range or shard.
- Batch local updates and merge them less frequently.
- Replace one global hot counter with per-CPU or per-thread counters.
- Keep synchronization variables separate from unrelated hot data.
- Reduce lock hold times and avoid repeatedly writing shared metadata.
- Recheck NUMA placement when threads and pages span sockets.
Do not add padding or weaken memory ordering solely because a benchmark improved once. Confirm that the program remains correct, measure memory overhead, and test on the processor families and deployment topologies that matter.
Common Misconceptions
“Cache coherence makes all shared-memory code safe.” Coherence coordinates cached copies; it does not prevent data races, lost updates, deadlocks, or incorrect publication. Use language-level atomics, mutexes, or another valid synchronization primitive.
“A cache miss always means DRAM access.” A miss in one cache can be satisfied by a shared cache or another core’s cache through the coherence fabric. The latency depends on the hierarchy and topology.
“False sharing means the variables have the same value.” They can contain completely unrelated values. False sharing is about sharing a physical cache line, not sharing a logical object or value.
“More cores always increase throughput.” Additional cores help when work is parallel and the cost of synchronization, memory bandwidth, coherence, and locality does not dominate. Benchmark the complete workload rather than extrapolating from core count.
Related Articles
- NUMA and memory locality in multicore systems
- Concurrency models in modern programming languages
- Program execution lifecycle: how CPU and RAM work together
- CXL memory pooling and fabric-attached memory
- Caching fundamentals and invalidation
Changelog
Published December 3. Initial explainer on cache-line coherence, MESI-family protocols, memory ordering, and false sharing.

