Notes
All notes

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:

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
QQuestionWhy not bypass caches for shared data?
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:

  1. Write propagation: a write eventually becomes visible to all cores.
  2. Write serialization: all cores see writes to the same location in the same order.
  3. 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).

QQuestionDoes coherence guarantee that a write is visible immediately?
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:

Remote events:

The key trick is E: a core that loads a line no one else has can write it later without any bus transaction.

QQuestionWhy does a write to an E-state line need no bus traffic?
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:

QQuestionWhy does invalidation dominate over update protocols?
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
QQuestionTwo threads write different 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.

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.

QQuestionDoes x86 need a fence between two loads?
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:

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
QQuestionWhy is a contended atomic so much slower than an uncontended one?
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:

Fixes:

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); }
};
QQuestionWhy does a ticket lock guarantee fairness but still scale poorly?
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:

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.

QQuestionWhen is padding a bad idea?
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

QQuestionA parallel counter array scales badly even with atomics. What are the

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.