Cache Coherence and Multiprocessors (COA Core #6)
Two cores, two private caches, one memory location. Core A writes it; core B has the old value in its cache. Without a protocol, B reads stale data forever. Cache coherence is the hardware contract that prevents this, and false sharing is what happens when that contract is applied at cache-line granularity instead of variable granularity.
Shared-memory multiprocessors
A shared-memory machine gives all cores one physical address space. Two common layouts:
- UMA (uniform memory access): every core reaches memory at the same latency. Small servers, older SMP systems.
- NUMA (non-uniform): memory is attached to sockets; local access is faster (roughly 80–120 ns vs 140–250 ns remote).
Each core has private L1 and usually private L2 caches; the L3 may be shared. Private caches are the performance win and the coherence problem: the same line can be present in several caches, and a write in one must not leave the others stale.
int x = 0;
// core 0
x = 1;
// core 1
printf("%d\n", x); // must eventually print 1, not a stale 0
ASolution
That would make every shared access a memory access, losing the locality that makes caches useful. Coherence keeps caching while preserving the illusion of one memory.
What coherence guarantees
A coherent memory system provides:
- Write propagation: a write eventually becomes visible to all cores.
- Write serialization: all cores see writes to the same location in the same order.
- Single-writer, multiple-reader per line: at any time, a line is either readable by many or writable by one.
Coherence is per location, not per program. It does not order accesses to different locations; that is memory consistency (covered below).
ASolution
No. It guarantees eventual visibility and a single order. A core may see its own write before others do, and the delay is bounded but not zero.
MESI
MESI is the classic invalidation-based snooping protocol. Each cache line is in one of four states:
| State | Meaning | Clean/dirty | Other copies? |
|---|---|---|---|
| Modified | this cache has the only copy, and it is dirty | dirty | no |
| Exclusive | this cache has the only copy, clean | clean | no |
| Shared | clean, may be in other caches | clean | yes |
| Invalid | not present / stale | — | — |
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, circle, minimum size=1.15cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[b, fill=red!18] (m) at (0,0) {M};
\node[b, fill=green!18] (e) at (3.0,0) {E};
\node[b, fill=blue!15] (s) at (6.0,0) {S};
\node[b, fill=gray!15] (i) at (9.0,0) {I};
\draw[a] (e) -- node[above, font=\tiny] {PrWr} (m);
\draw[a] (m) -- node[below, font=\tiny] {BusRd / flush} (s);
\draw[a] (e) -- node[below, font=\tiny] {BusRd} (s);
\draw[a] (s) -- node[above, font=\tiny] {BusUpgr} (m);
\draw[a] (s) -- node[above, font=\tiny] {BusRdX} (i);
\draw[a] (m) -- node[right, font=\tiny] {BusRdX / flush} (i);
\draw[a] (i) to[bend left=45] node[below, font=\tiny] {PrRd / BusRd} (s);
\draw[a] (i) to[bend right=55] node[above, font=\tiny] {PrWr / BusRdX} (m);
\end{tikzpicture}
Local events:
- PrRd on I: issue BusRd. If another cache shares or owns the line, the line becomes S; if no one has it, the line becomes E.
- PrWr on I: issue BusRdX (read for ownership); the line becomes M.
- PrWr on S: issue BusUpgr (invalidate others); becomes M.
- PrWr on E: silent transition to M; no bus traffic, because no other copy exists.
Remote events:
- BusRd from another core: M flushes the data and goes to S; E goes to S; S stays S.
- BusRdX (or BusUpgr): every other copy goes to I; the requester gets the line and becomes M.
The key trick is E: a core that loads a line no one else has can write it later without any bus transaction.
ASolution
E means this is the only cached copy, so no other cache can hold stale data. The write can proceed silently and move the line to M.
Ownership, snooping, and directories
In M state, the cache is the owner: it must supply the data on a read from another core and write it back when evicting. Memory may be stale while a line is modified.
Two implementation styles:
| Style | How it works | Scales to |
|---|---|---|
| Snooping | every cache watches a shared bus and reacts | small core counts (bus bandwidth limits) |
| Directory | a directory tracks sharers per line; requests are forwarded | large core counts |
Snooping is simple and fast for a few cores. Directories avoid broadcasting to every core, which matters at 64+ cores where a bus would be a bottleneck.
Protocols also differ in action:
- Invalidation: other copies are dropped. Simple, and the standard for CPUs.
- Update: other copies are updated with the new value. More traffic, used in some GPUs and specialized systems.
ASolution
Most writes are not read soon by other cores. Updating every sharer wastes bandwidth; invalidating costs one transaction and lets a future reader fetch only if it actually needs the data.
False sharing
The cache is coherent at line granularity (64 bytes), not variable granularity. Two threads writing two different variables that happen to share a line cause the line to bounce between cores.
struct Shared {
std::atomic<long> a{0}; // same 64-byte line
std::atomic<long> b{0};
};
Shared s;
// thread 0: for (...) s.a.fetch_add(1, std::memory_order_relaxed);
// thread 1: for (...) s.b.fetch_add(1, std::memory_order_relaxed);
There is no data race: the variables are independent and atomic. There is still
coherence traffic: every write to a invalidates the line in the other core, so the
next write to b must fetch it back exclusively.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=1.4cm, minimum height=0.5cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=blue!10] (l1) at (0,0.8) {core 0 L1\\[a]};
\node[b, fill=orange!15] (l2) at (4.6,0.8) {core 1 L1\\[a]};
\node[b, fill=gray!10] (mem) at (2.3,-0.5) {memory\\line: a b};
\draw[a, red!65] (l1) -- node[above, font=\tiny] {invalidate} (l2);
\draw[a] (mem) -- (l1);
\draw[a] (mem) -- (l2);
\node[font=\scriptsize, anchor=north] at (2.3,-1.0) {one line, two writers: it ping-pongs};
\end{tikzpicture}
Fix: put each hot variable on its own line.
struct alignas(64) Padded {
std::atomic<long> v{0};
};
Padded p0, p1; // 64-byte separation
C++17 provides std::hardware_destructive_interference_size (often 64) for this,
though support varies. A portable habit is alignas(64) plus a compile-time check
against alignof(std::max_align_t).
The same effect appears with an array of counters indexed by thread id, a struct of
per-thread statistics, and adjacent fields updated by different threads. The symptom
is a parallel loop that scales poorly while the CPU is busy in cache-coherence
traffic (visible as high HITM/snoop counts in perf c2c).
perf c2c record ./app
perf c2c report
ints in the same struct with no locks.Is that a data race?
ASolution
Not if they are different objects and neither reads the other. It is a coherence problem, not a C++ data race. The fix is padding, not a mutex.
Memory consistency
Coherence orders accesses to one location. Consistency orders accesses to different locations as seen by other cores.
- Sequential consistency (SC): the result is as if all operations executed in a single global order respecting each core’s program order. Easiest to reason about, slowest to implement.
- Total Store Order (TSO): x86. Stores go to a store buffer; a core can read its own store early, and a later load can pass an earlier store to a different address. Loads are not reordered with loads, stores not with stores.
- Weak / release consistency: ARM, POWER, RISC-V. Loads and stores can reorder freely unless separated by fences or acquire/release operations.
Dekker’s example shows the difference:
// core 0 // core 1
x = 1; y = 1;
r1 = y; r2 = x;
Under SC, at least one of r1, r2 must be 1. Under x86 TSO, both can be 0, because
each core’s store sits in its store buffer while the load executes.
Fences restore order:
std::atomic_thread_fence(std::memory_order_seq_cst);
or use acquire/release atomics, which are cheaper than a full fence on most architectures.
ASolution
No. TSO does not reorder loads with loads. It needs a fence (or a locked instruction) to prevent a store followed by a load from being observed out of order.
Atomic instructions
Coherence makes line ownership exclusive for writes. Atomics build on that:
- Test-and-set: write 1 and return the old value, atomically.
- Compare-and-swap (CAS): if the value equals an expected value, replace it.
- Fetch-and-add: return the old value and increment atomically.
- LL/SC (load-linked/store-conditional): ARM, RISC-V; the store fails if the line changed since the load.
x86 implements these with a lock prefix, which asserts a cache-line lock for the
duration. On modern CPUs that is a coherence transaction, not a bus lock, but it is
still expensive:
| Operation | Uncontended cost |
|---|---|
| normal load | ~4 cycles (L1) |
lock add |
~20 cycles |
contended lock cmpxchg |
hundreds–thousands of cycles |
ASolution
The line must move between cores. Each transfer costs an interconnect round trip and serializes the cores that want the same line.
Locks at the hardware level
A spinlock is a loop around an atomic operation:
class Spinlock {
std::atomic<bool> locked{false};
public:
void lock() {
while (locked.exchange(true, std::memory_order_acquire)) {
// spin
}
}
void unlock() { locked.store(false, std::memory_order_release); }
};
Problems with the naive version:
- Cache-line contention: every spinner hammers the same line with read-modify-write (RMW) operations.
- No fairness: one core can win repeatedly.
Fixes:
- Test-and-test-and-set: spin on a plain read; only attempt the RMW when the lock looks free.
- Ticket lock:
nextandservingcounters give FIFO fairness; still one shared line. - MCS / queued lock: each waiter spins on its own node, so contention moves to per-core lines; scales to many cores.
struct TicketLock {
std::atomic<unsigned> next{0}, serving{0};
void lock() {
unsigned t = next.fetch_add(1, std::memory_order_relaxed);
while (serving.load(std::memory_order_acquire) != t) { }
}
void unlock() { serving.fetch_add(1, std::memory_order_release); }
};
ASolution
Waiters are served in order, but all of them read the same serving line, so
every release broadcasts an invalidation to every waiter.
Cache-line alignment and padding
Two tools, for two different goals:
- Avoid false sharing (destructive interference): separate hot variables by a line.
- Improve packing (constructive interference): keep data used together on the same line.
struct alignas(64) PerThread {
long counter = 0;
char pad[64 - sizeof(long)];
};
PerThread stats[8]; // one line per thread
Padding wastes memory. Use it only for hot, frequently written, per-thread data, and measure before and after. A usual pattern is per-thread counters padded and separated, summed at the end, which turns millions of coherence transactions into a few.
ASolution
When the data is read-only or rarely written, padding only wastes cache capacity. It also hurts when a later pass reads all the counters, because now it touches eight lines instead of one.
Bugs and edge cases
- Atomic does not mean contention-free.
std::atomicfixes races, not false sharing. - Coherence is not consistency. A coherent machine can still reorder independent accesses.
- Assuming SC on x86. TSO allows store-load reordering; use fences or acquire/release.
- Padding everything. It can increase cache misses and memory use with no gain.
- Reading a modified line from memory. In M state, memory may be stale; the owner must supply the data.
- Ignoring NUMA. A shared line in a remote node’s cache costs more to fetch.
- Assuming a lock is free when uncontended. It still costs an atomic RMW and a possible line transfer.
two likely causes?
ASolution
False sharing between adjacent counters, and contention on one shared counter. Pad per-thread counters and aggregate at the end.
Next: Performance and Optimization (COA Core #7) — CPI, Amdahl, locality, and the cost of a branch miss.