Lecture 14 · Cache Coherence

Parallel Computing · Lecture 14。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 14 (Nov 11), slide deck 14_coherence (45 slides). First lecture of the last unit, “shared memory done right”. Sources: the public Fall 2025 slides; D. Culler, J. P. Singh, A. Gupta, Parallel Computer Architecture: A Hardware/Software Approach (Morgan Kaufmann, 1999), ch. 5 and 8; D. J. Sorin, M. D. Hill, D. A. Wood, A Primer on Memory Consistency and Cache Coherence (2nd ed., Morgan & Claypool, 2020); J. L. Hennessy, D. A. Patterson, Computer Architecture: A Quantitative Approach, 6th ed., ch. 5. Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro, 8 performance cores in two clusters of 4, 128-byte cache lines; clang 21, macOS 27). The protocols themselves are studied in a simulator, because a program cannot watch the hardware’s coherence states directly. Code: code/lecture14/. Reading time: ~70 minutes for the prose; ~10 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why private caches break the “one shared memory” abstraction: the cache coherence problem (缓存一致性问题). Explain why locks cannot fix it.
  2. State the definition of coherence (a per-address serial order) and the two invariants that implement it: single-writer/multiple-reader (SWMR, 单写多读) and data-value (数据值不变式).
  3. Explain how a snooping (监听) protocol works, and why write-through invalidation is correct but too expensive.
  4. Trace the MSI and MESI protocols step by step: the state of a line in every cache, the bus transaction, and where the data comes from.
  5. Explain how a directory (目录) avoids broadcasts, and when it does not help.
  6. Predict the cost of a sharing pattern (private, read-shared, producer-consumer, migratory) and recognize false sharing (伪共享). Explain how line size trades spatial locality against false sharing, and fix false sharing in code.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 1–3: caches, lines, locality.
    • Lecture 6: communication, inherent vs. artifactual (人为的) communication.
    • Some experience with threads that share variables.
  • Scope: this lecture is about one address at a time: does everyone agree on the values of address X? Lecture 15 asks the harder question about different addresses: in what order may other cores see my writes to X and Y? That is memory consistency.

0.3 Section → code map

SectionIdeaDemo in code/lecture14/
§2the coherence problem, made visible01_protocols.py Part A (uses coherence.py)
§4.1write-through + invalidate01_protocols.py Part B
§4.3–§4.5MSI and MESI, traced and checked01_protocols.py Parts C–F
§4.6, §5traffic per sharing pattern; directories02_sharing_patterns.py Parts A–B
§6.3line size vs. miss types02_sharing_patterns.py Part C
§6.2false sharing, latency, true sharing on real cores03_false_sharing

Run them all with cd code/lecture14 && make run (~12 seconds).

0.4 Notation

  • Line (缓存行): the unit a cache stores and moves: 64 bytes on most x86 chips, 128 bytes as reported on the author’s Apple M4 Pro.
  • P1, P2, …: processors (cores). $: a cache. X, Y: addresses.
  • PrRd / PrWr: a load / store by the local processor. BusRd / BusRdX / BusWB: bus transactions: read, read-exclusive (read with intent to modify), write-back.
  • States: M (modified), E (exclusive clean), S (shared), I (invalid).

1. Review: what a cache does (slides 3–8)

Caches take a large share of a modern die: more than 30% on an Intel Core i7 (slide 3). They work because programs have locality (局部性) (slides 4–5):

  • spatial locality: loading one byte brings its whole line, so nearby accesses hit;
  • temporal locality: repeated accesses to the same address hit.

Misses come in “3 Cs”:

  • cold (first access);
  • capacity (the working set does not fit);
  • conflict (too many lines map to the same set).

This lecture adds a fourth kind: coherence misses.

Each line in a cache carries a tag (which address it holds), its data, and some state bits (slide 6): valid, and dirty for a write-back cache. Two policies matter for this lecture:

  • Write-through vs. write-back. A write-through cache sends every write to memory immediately. A write-back cache updates only its own copy and marks the line dirty; memory is updated when the line is evicted.

  • Write-allocate vs. write-no-allocate. On a write miss, a write-allocate cache first loads the line (slide 7):

    1. pick a slot, writing back a dirty victim if needed;
    2. load the whole line from memory;
    3. update the 4 bytes;
    4. mark the line dirty.

    A write-no-allocate cache sends the write onward without loading the line.

Modern CPUs use write-back, write-allocate caches in a hierarchy. Slide 8 shows Intel’s Skylake (2015):

  • 32 KB L1 and 256 KB L2 per core, private;
  • an 8 MB L3 shared by all cores, in one bank per core on a ring;
  • 64-byte lines.

On the author’s M4 Pro, macOS reports:

  • 128 KB of L1 data cache per performance core;
  • a 16 MB L2 shared by each cluster of 4 performance cores, two clusters in all;
  • 128-byte lines.

Every core has private caches, and that is where the trouble starts.


2. The cache coherence problem (slides 9–15)

2.1 The abstraction we want (slides 9–10)

In the shared-address-space programming model (Lecture 2), threads communicate by reading and writing shared variables. Thread 1 stores to X; later, thread 2 loads X and sees the new value. That is how locks, flags and shared data structures work. The natural expectation of memory (slide 10):

Reading a value at address X returns the last value written to address X by any processor.

On a single processor this is easy: only one source writes. The exception is I/O devices writing memory by DMA (direct memory access). Slide 14 notes that even then the OS must take care.

2.2 Private caches break it (slides 11–13)

Each processor keeps copies of memory lines in its own cache. Demo 01 runs slide 11’s sequence on three write-back caches with no protocol at all. Each cache holds one line, so P1’s last access evicts X:

  action             P1 P2 P3 bus   data from    value                        mem[X]
  P1 read X          C  -  -  --    memory       0                            0
  P2 read X          C  C  -  --    memory       0                            0
  P1 write X = 1     D  C  -  --    hit                                       0
  P3 read X          D  C  C  --    memory       0  STALE (last write: 1)     0
  P3 write X = 2     D  C  D  --    hit                                       0
  P2 read X          D  C  D  --    hit          0  STALE (last write: 2)     0
  P1 read Y          C  -  -  --    memory       0                            1

(C = clean copy, D = dirty copy.)

  • P1’s write of 1 sits in P1’s cache, so P3 reads the old 0 from memory.
  • P3 then writes 2 into its own copy, and P2 keeps reading its stale 0.
  • When P1 finally evicts X, memory receives P1’s 1, which is not even the latest value.

At the end, address X has three different values in three places: P2’s cache holds 0, memory holds 1, P3’s cache holds 2.

Is this a mutual-exclusion problem? No (slide 12). The accesses above are not even concurrent. Adding locks would not help, because the problem is replication: storage is split between memory and caches (slide 13), and nothing keeps the copies in agreement. The hardware itself must fix it.

2.3 What does “last” mean? (slide 15)

“The last value written” sounds obvious, but in a parallel machine it is not:

  • Two processors may write at the same moment.
  • A read may come so soon after another processor’s write that the news of the write cannot physically have arrived yet.

In a sequential program, “last” means last in program order, not in time. For a parallel program we need a definition that orders operations from different processors.


3. What coherence means, and how to implement it (slides 16–20)

3.1 The definition (slide 16)

A memory system is coherent if, for each memory location, the results of a parallel execution are consistent with some hypothetical serial order of all the operations on that location, such that:

  1. operations issued by any one processor appear in this order in the order that processor issued them (program order is respected); and
  2. every read returns the value written by the most recent write to the location in this serial order.

Note what it does not say. It does not say the serial order follows real time, and it does not relate the orders of different locations. Each address has its own serial order. Ordering across addresses is consistency, Lecture 15.

3.2 The invariants that implement it (slide 17)

Hardware implements the definition by dividing each address’s lifetime into epochs, and keeping two invariants:

  • Single-writer, multiple-reader (SWMR). At any time, either exactly one processor may read and write the line (a read-write epoch), or any number of processors may read it (a read-only epoch). Never both.
  • Data-value (write serialization). The value at the start of an epoch equals the value at the end of the last read-write epoch.

So writes to one address happen one at a time, and every reader in a later epoch sees the latest of them.

3.3 Software vs. hardware, and shared caches (slides 18–20)

Coherence can be built at different granularities:

  • In software, per page: the OS uses page faults to track who writes what. This is used to make a cluster of workstations look like one shared memory, but false sharing at 4 KB granularity is a severe performance problem.
  • In hardware, per cache line: snooping (§4) or directories (§5).

The simplest hardware fix is to have no private caches: one cache shared by all processors (slide 19). There is nothing to keep coherent. Sharing even has benefits: one processor’s load can prefetch data another needs, and overlapping working sets fit once. But a shared cache serves many clients, so it is slower, contended, and suffers interference. It cannot be the small, fast cache next to each core. Sun’s Niagara 2 (slide 20) connects 8 cores to banks of a shared L2 through a crossbar that takes about the area of a whole core. That is the price of making a shared cache reachable by everyone.


4. Snooping protocols (slides 21–35)

4.1 The idea, and the simplest protocol (slides 21–23)

In a snooping scheme, every coherence-related operation is broadcast to all cache controllers over a shared interconnect, traditionally a bus. Every controller watches (“snoops”) the broadcasts and reacts according to the protocol. Each controller now serves two masters (slide 21):

  1. loads and stores from its own processor;
  2. coherence messages from the interconnect.

The simplest correct protocol (slide 22) uses write-through caches. On every write, the controller sends the write to memory and broadcasts an invalidation; other caches drop their copy. Their next read misses and fetches the new value from memory. Demo 01, Part B, runs slide 22’s example:

  action             P1 P2 bus              data from    value
  P1 read X          V  -  BusRd            memory       0
  P2 read X          V  V  BusRd            memory       0
  P1 write X = 100   V  I  BusWr (+inval)   hit
  P2 read X          V  V  BusRd            memory       100

It is correct, but every single write goes to memory (slide 23). A thousand writes by one processor to one line cost 1,000 bus transactions in demo 01; with the write-back protocol below they cost 1. Write-back caches absorb most writes as hits, so we want coherence for write-back caches.

4.2 Write-back caches need ownership (slides 24–27)

With write-back caches, the latest value may live only in some processor’s cache. So the dirty state takes on a second meaning, exclusive ownership. A line in the modified state is:

  • the only valid copy anywhere, so its owner can write it without telling anyone;
  • the owner’s responsibility: when another processor asks for the line, the owner must supply the data, because memory is stale.

An invalidation-based protocol (slide 26) follows from this. A processor may write only a line it holds in the modified state. To get there, it broadcasts a request for exclusive access, and every other cache that sees the request invalidates its copy.

4.3 MSI (slides 28–33)

MSI has three states per line in each cache:

  • I (invalid): not here, or not usable;
  • S (shared): a valid, clean copy; others may have copies too; memory is up to date;
  • M (modified): the only valid copy; dirty.

It reacts to two processor events (PrRd, PrWr) and three bus transactions:

  • BusRd: get a copy, no intent to modify;
  • BusRdX: get a copy with intent to modify (read-exclusive);
  • BusWB: write a dirty line back to memory.

Demo 01, Part F, tabulates the state machine from the simulator’s behaviour: it puts a line in each state and applies each event. The result is slide 29’s diagram as a table:

stateeventnextaction
IPrRdSBusRd
IPrWrMBusRdX
SPrRdS— (hit)
SPrWrMBusRdX
SBusRdS—
SBusRdXI— (invalidate)
MPrRd, PrWrM— (hit)
MBusRdSflush: supply the data, write it back
MBusRdXIflush, then invalidate

Slide 31’s example, as demo 01 prints it, matches the slide row by row:

  action             P1 P2 P3 bus              data from
  P1 read X          S  -  -  BusRd            memory
  P3 read X          S  -  S  BusRd            memory
  P3 write X = 1     I  -  M  BusRdX           memory
  P1 read X          S  -  S  BusRd            P3's cache
  P1 read X          S  -  S  --               hit
  P2 write X = 2     I  M  I  BusRdX           memory

Three details:

  • A write to a line held in S still needs a BusRdX (row 3, slide 33’s “why?”). The writer has a valid copy, but other caches may too, and SWMR requires invalidating them before the write. The slides’ BusRdX also re-fetches the data, which is wasteful. Many real protocols send a data-less upgrade instead.
  • M → S on a remote read (row 4). P3 supplies the data to P1, and memory is updated, so both copies are clean and shared. Slide 31 asks why M must drop to S. If P3 stayed in M, it could write again without telling P1, whose copy would silently go stale.
  • Coherence adds latency to these misses: row 4’s data must come from another cache, not memory.

Why MSI is coherent (slide 32):

  • SWMR: only one cache can be in M. Getting there broadcasts a BusRdX that invalidates all other copies, and S copies are read-only.
  • Data-value: on BusRd and BusRdX, the M copy supplies the data. The bus serializes all transactions, and that order is the “hypothetical serial order” of the definition.

Demo 01 checks both invariants after every one of 100,000 random accesses by 4 processors, with caches small enough to force evictions. MSI, MESI and write-through invalidation never violated either one. Without a protocol, 45,955 of the reads were stale.

4.4 MESI (slides 34–35)

MSI has an inefficiency that hits even programs with no sharing at all. Reading an address and then writing it, the most common pattern for private data, costs two transactions:

  1. a BusRd (I → S);
  2. a BusRdX (S → M).

MESI (“not Messi!”) adds a state:

  • E (exclusive clean): this is the only cached copy, but it is not modified, so memory is valid.

A read miss gets E if no other cache asserts that it has a copy (a “shared” signal on the bus); otherwise it gets S. A write to an E line moves it to M without any bus transaction, since nobody else has a copy to invalidate. MESI separates exclusivity (E or M) from ownership of dirty data (M only).

Measured in demo 01, Part D: four processors each read-then-write their own 1,000 lines.

  • MSI: 8,000 bus transactions.
  • MESI: 4,000, the BusRdX transactions are gone.

On slide 31’s trace, which has real sharing, MESI and MSI send exactly the same messages: E only helps when nobody else has the line.

Real CPUs use further variants:

  • MOESI (AMD): an O (owned) state lets a dirty line be shared without writing it back.
  • MESIF (Intel): an F (forward) state names one sharer to answer requests.

The principle is the same throughout: a single writer, and the latest data supplied by whoever has it.

4.5 What coherence costs, by sharing pattern

Demo 02, Part A, runs six sharing patterns on 8 processors with 64-byte lines and counts traffic per 1,000 accesses:

patternMSI: bus transactions / invalidationsMESI
private data, read then write40 / 020 / 0
read-only shared table20 / 020 / 0
producer-consumer (one writes a buffer, all read it)1000 / 8401000 / 840
migratory (each processor in turn reads and writes a counter)1000 / 499999 / 499
false sharing (each writes its own word, all words in one line)938 / 875938 / 875
the same counters, each on its own line2 / 01 / 0

Private and read-only data cost almost nothing once cached. Data that changes hands costs a transaction, and usually invalidations, every time it moves. For the producer-consumer and migratory patterns this is inherent communication: the algorithm really does move values between processors. False sharing costs the same, yet no word is ever shared. It is pure artifactual communication, which padding removes completely.


5. Scaling coherence with directories (slides 36–37)

Snooping broadcasts every transaction. Every other cache must look up its tags for every miss anywhere in the system, so the bus or ring must carry all of them, and the lookups grow with P (slide 36). For a few cores this is fine. For dozens or hundreds it is not.

A directory keeps, for each line, a record of its state in all caches. For example: “modified in cache 7”, or “shared by caches {2, 5, 9}”. The record lives at a fixed place, the line’s home. A cache that misses sends a point-to-point request to the home. The home then sends messages only where they are needed:

  • a forward to the current owner;
  • invalidations to the actual sharers, which reply with acknowledgements.

The invariants are unchanged; only the way they are enforced changes. The directory is the serialization point for its lines.

Intel’s Core i7 uses its inclusive L3 as the directory (slide 37). Every line in any L2 is also in the L3, so the L3 can keep, for each line, a bit per core saying which L2s hold it. Coherence messages go only to those L2s, over a ring, not a bus.

Demo 02, Part B, counts both costs for the same traces under MESI:

  • snooping: the tag lookups the other P − 1 caches perform;
  • directory: the point-to-point messages a directory protocol would send.
patternP = 4: snoop / dirP = 16P = 64
private data60 / 40300 / 401260 / 40
producer-consumer3000 / 370015000 / 386563000 / 3906
migratory2998 / 349714991 / 349762961 / 3497
false sharing2626 / 337514532 / 384461036 / 3844

(per 1,000 accesses)

Snooping work grows linearly with P for every pattern, even private data. Directory messages stay flat, because each miss involves only the parties that actually hold the line. A directory is not free, though:

  • At small P it sends more messages than a bus broadcast: a request, then forwards, invalidations and acknowledgements as separate messages.
  • When a line is shared by everyone and then written, the directory must invalidate every sharer. Demo 02 counts 7, 30 and 122 messages per producer write at P = 4, 16 and 64.
  • It costs storage: a full bit vector needs P bits per line.

So directories scale well for programs whose data is shared by few processors at a time, and that describes most well-written parallel programs.


6. What coherence means for the programmer (slides 38–44)

6.1 Communication shows up as memory latency (slides 39–40)

On a multiprocessor, communication does not look like messages. It looks like slower memory accesses. The average memory access time (AMAT) is

AMAT = Σ frequency of access × latency of access

and it is larger on a multiprocessor than on a uniprocessor:

  • miss rates rise, because data is invalidated by other processors;
  • some accesses must fetch lines from another core’s cache;
  • on a NUMA system (non-uniform memory access, 非一致内存访问), some memory is remote.

Slide 39’s Core i7 / Xeon 5500 latencies:

  • L1 hit: ~4 cycles;
  • L2 hit: ~10 cycles;
  • L3 hit, line unshared: ~40 cycles;
  • L3 hit, line shared with another core: ~65 cycles;
  • L3 hit, line modified in another core: ~75 cycles;
  • local DRAM: ~120 cycles;
  • remote DRAM: ~400 cycles.

Even a fraction of a percent of accesses at those latencies matters. Tools such as VTune (slide 40), or Instruments on macOS, count these events.

Demo 03 measures the “modified in another core” case on the author’s machine with a ping-pong. Two threads pass a token through one atomic variable, so every hand-off moves the line from one core’s cache to the other’s. One hand-off took 37–91 ns across runs (medians 43–55 ns), depending on which two cores the OS chose. The 8 performance cores sit in two clusters of 4. Compare ~2 ns for an atomic increment of a line that stays in one’s own L1.

6.2 False sharing, measured (slides 41–43)

False sharing happens when processors write different addresses that lie in the same cache line (slide 43). The line “ping-pongs” between the writers’ caches, and each transfer is real coherence traffic. Yet the program shares nothing; the communication is an artifact of lines being bigger than the data. The textbook example is an array of per-thread counters (slides 41–42):

int myPerThreadCounter[NUM_THREADS];          // all counters in one or two lines

struct PerThreadState {                        // the fix: one counter per line
    int myPerThreadCounter;
    char padding[CACHE_LINE_SIZE - sizeof(int)];
};

Slide 42 runs 8 threads on a 4-core Intel machine: 14.2 s packed vs 4.7 s padded. Demo 03 runs the same experiment on the author’s machine, and two surprises came out of it.

Surprise 1: slide 42’s loop hardly suffers here. With plain (*counter)++ through a volatile pointer, packed counters were at most 1.5–3.7× slower than padded ones. A likely explanation, not verified at the level of the microarchitecture: each core keeps its recent stores in its store buffer (存储缓冲区), reads them back from there, and commits them in batches whenever it holds the line. So the line moves far less often than once per increment. Store buffers return in Lecture 15 as the reason memory consistency is hard.

With atomic increments, false sharing is brutal. An atomic read-modify-write (fetch_add) must hold the line in its own cache for every increment. Same per-thread counters, nanoseconds per increment per thread:

threadspacked (4 B apart)padded to 64 Bpadded to 128 Bpacked / 128
11.81.91.81.0×
27.61.81.94.1×
441.61.91.922×
82348.32.2105×

At 8 threads, each increment costs about one line hand-off, and the line is fought over by 8 cores. Across runs the packed/padded ratio at 8 threads was 93–105×.

Surprise 2: how much padding is enough? Demo 03 tried to find the unit of coherence by timing: put counters d bytes apart, and find where the slowdown stops.

  • With 2 threads, counters stop interfering at 64 B.
  • With 8 threads, they stop at 96–128 B, and 64-byte padding is still 2.4–3.7× slower than 128-byte padding.

macOS reports 128-byte lines. No single line size explains both observations. Candidates include coherence tracked at a finer grain than the line, prefetching of neighbouring lines, and the two clusters; we could not tell them apart. The practical rule held in every run: pad to the line size the system reports (128 B here), or more. The C++ library even says so: std::hardware_destructive_interference_size is 256 on this compiler, to cover all Apple chips. Code written for x86 with 64-byte padding is not safe on Apple silicon.

True sharing cannot be padded away. If all threads increment one atomic counter, each increment again needs the line: 173–230 ns per increment at 8 threads. The only fix is to communicate less. Count in a local variable and add to the shared counter once at the end: 0.4 ns per increment. This is the per-thread accumulation pattern of Lectures 4 and 8, and the reason reductions are done in trees.

6.3 Line size: spatial locality vs. false sharing (slide 44)

Larger lines bring more neighbouring data per miss, which helps programs with spatial locality. They also make it more likely that data used by different processors shares a line. Slide 44 (from Culler, Singh and Gupta) splits misses into cold, capacity/conflict, true sharing and upgrade, for four applications as the line grows from 8 to 256 bytes. Demo 02, Part C, does the same with the simulator. It classifies every miss by cause. A coherence miss counts as true sharing if the word being read was really written by another processor since this cache lost the line, and as false sharing otherwise.

  • An Ocean-like grid solver: rows are split into blocks, one per processor, and only the boundary rows are shared. Doubling the line halves the cold and capacity misses, from 225 to 5 per 1,000 accesses between 8 B and 256 B, and true sharing stays tiny. The bytes moved stay at ~150 KB at every line size, because the row blocks are line-aligned. This is perfect spatial locality.
  • A radix-sort-like scatter: ownership of output elements alternates every 2 ints, so neighbouring words belong to different processors. False-sharing misses rise from 0 (8-byte lines) to 492 per 1,000 accesses (256-byte lines), and the bytes moved grow from 48 KB to 2.2 MB, about 46×.

The lesson for programmers is to make each processor’s data contiguous and line-aligned:

  • partition arrays into blocks, not interleaved elements (Lecture 5’s blocked vs. interleaved assignment, now with a new reason);
  • pad per-thread data to whole lines;
  • align partition boundaries to line boundaries.

7. Summary of the lecture (slide 45)

  • The coherence problem exists because the abstraction of one shared address space is implemented by many storage units, memory and every private cache, with data replicated for performance.
  • Snooping coherence: whenever a cache operation could affect coherence, the controller broadcasts it, and all other controllers react. Hardware architects try to minimize the overhead. Software developers must beware artifactual communication, false sharing above all.
  • Snooping’s scalability is limited by broadcasting to every cache. Directories scale coherence by tracking sharers and sending point-to-point messages.

Summary

  • Private caches replicate data. Without a protocol, processors read stale values (demo 01: 45,955 stale reads in 100,000 random accesses). This is a replication problem, not a race, so locks cannot fix it.
  • Coherence means each address has a serial order of its operations that respects every processor’s program order, with each read returning the latest write in that order. Hardware implements it with the SWMR and data-value invariants.
  • Write-through + invalidate is correct but sends every write to memory. MSI gives a writer exclusive ownership (M) via BusRdX and makes the owner supply data on a remote miss. MESI adds E so that private read-then-write data needs one transaction instead of two. The bus order is the serial order.
  • Directories replace broadcasts with point-to-point messages to actual sharers. Traffic stays flat as P grows unless data is widely shared and then written.
  • On real cores, a line hand-off costs ~40–90 ns versus ~2 ns for an L1 hit. False sharing of atomically updated per-thread counters cost ~100× at 8 threads. Padding to 128 B removes it on this machine; 64 B is not enough. True sharing can only be reduced by communicating less, for example local accumulation.
  • Longer lines cut cold misses but create false sharing when processors’ data interleave. Keep each processor’s data contiguous and line-aligned.

Common pitfalls

  • Thinking coherence makes programs race-free. Coherence guarantees each address has one agreed history. It does not make count++ atomic (two increments can still interleave), and it says nothing about the order in which other cores see writes to different addresses (Lecture 15).
  • Padding to 64 bytes because “cache lines are 64 bytes”. On Apple silicon the OS reports 128-byte lines, and 64-byte padding was 2.4–3.7× slower than 128-byte padding in demo 03. Use std::hardware_destructive_interference_size, or the platform’s line size.
  • Putting per-thread data in one array of small structs. struct { int count; } stats[NUM_THREADS]; is the slide-41 bug. Pad each element, or keep the data in each thread’s own stack or local variables until the end.
  • Interleaved work assignment over shared output arrays. Giving thread t the elements i ≡ t (mod P) of an output array makes every line written by several threads. Give each thread a contiguous block instead.
  • Fixing true sharing with padding. If all threads update the same variable, no padding helps. Reduce the number of updates instead: local accumulation, then one combine.
  • Benchmarking false sharing with a plain loop and concluding it does not matter. On some cores the store buffer hides most of it for plain stores, but atomics, locks and flags expose it fully.

Exercises

  1. Trace MSI. Three processors, one address X, initially uncached. Trace the states of X in P1–P3, the bus transaction and the data source for: P2 read X; P1 read X; P1 write X; P3 read X; P2 write X; P1 read X.

    Answer (1) P2 read: — S —, BusRd, from memory. (2) P1 read: S S —, BusRd, from memory. (3) P1 write: M I —, BusRdX (an upgrade from S), P2 invalidates. (4) P3 read: S I S, BusRd, data from P1's cache (P1 flushes, M → S, and memory is updated). (5) P2 write: I M I, BusRdX, from memory (it is up to date because both copies were S), P1 and P3 invalidate. (6) P1 read: S S I, BusRd, data from P2's cache. You can check this with `System(3, "MSI")` in `coherence.py`.
  2. MESI vs MSI. One processor reads and then writes each of 100 private lines; afterwards a second processor reads all 100 lines. How many bus transactions under MSI and under MESI?

    AnswerMSI: 100 BusRd + 100 BusRdX, then 100 BusRd for the second processor (each served by the first processor's cache, M → S), for 300 in total. MESI: 100 BusRd (getting E) + 0 for the writes (E → M is silent), then 100 BusRd, for 200 in total.
  3. Directory storage. A directory keeps a full bit vector (one bit per core) plus 2 state bits for every 64-byte line. What fraction of storage does it add for 64 cores? For 1,024 cores? Name one way real systems shrink it.

    Answer64 cores: 66 bits per 512-bit line, ≈ 13%. 1,024 cores: 1,026 bits per 512-bit line, ≈ 200%, more than the data itself. Real systems use limited pointers (record only a few sharers, and broadcast if more), coarse vectors (one bit per group of cores), or keep entries only for lines actually cached, a sparse directory like Intel's inclusive L3.
  4. Spot the false sharing. struct Stats { long hits; long misses; }; Stats s; Thread 1 increments s.hits in a loop and thread 2 increments s.misses. Why is this slow, and how would you fix it on the author’s machine?

    AnswerBoth fields are in the same 16 bytes, so the same line ping-pongs between the two cores on every update: false sharing. The best fix is to give each thread a local counter and write it to the struct once at the end. Otherwise, put each field on its own line: `struct Stats { alignas(128) long hits; alignas(128) long misses; };`. Use 128 bytes, not 64, on Apple silicon (demo 03).
  5. AMAT. A core’s loads hit L1 95% of the time (4 cycles); 4% hit L2 (12 cycles); 0.9% hit an unshared line in L3 (40 cycles); 0.1% hit a line modified in another core (75 cycles). What is the AMAT? If false sharing raises the last category to 2% (taken from the L1 hits), what is it then?

    AnswerBase: 0.95·4 + 0.04·12 + 0.009·40 + 0.001·75 = 3.8 + 0.48 + 0.36 + 0.075 ≈ 4.7 cycles. With 2% coherence misses: 0.931·4 + 0.48 + 0.36 + 0.02·75 = 3.72 + 0.48 + 0.36 + 1.5 ≈ 6.1 cycles. That is about 30% slower overall from a 2% change in where accesses are served.
  6. Assignment and line size. Eight threads each update a different subset of a shared int out[N]. Compare assigning element i to thread i mod 8 with giving each thread a contiguous block of N/8 elements, for 128-byte lines. Which elements, if any, are falsely shared in the blocked version?

    AnswerInterleaved: each 128-byte line holds 32 ints written by all 8 threads, so every line is falsely shared. Blocked: each thread's block is contiguous, so only lines that straddle a block boundary are shared. There are at most 7 such lines, and none at all if N/8 is a multiple of 32 and the array is 128-byte aligned.
  7. Why not locks? A student proposes to fix slide 11’s problem by wrapping every access to X in a lock. Explain why this cannot work without hardware coherence. Then explain why locks are still needed with coherence for X = X + 1 executed by two threads.

    AnswerWithout coherence, the lock itself is a memory location whose value is cached. Each processor could see the lock as free in its own stale copy, and even with the lock held correctly, the protected data would still be read from stale private copies. Locks rely on coherent memory, not the other way round. With coherence, each read and each write of X is ordered, but the read-modify-write sequence is not atomic: both threads can read the same old value before either writes. The lock (or an atomic instruction) provides atomicity, which coherence does not.
  8. Plain vs. atomic. Demo 03 found that packed per-thread counters slowed plain volatile increments by at most ~3.7×, but atomic increments by ~100×. Explain the difference in terms of when each kind of increment needs the line in its own cache.

    AnswerA plain store can wait in the core's store buffer, and the next load of the same address can take its value from there. The line is needed only when the buffered stores are written into the cache, which can happen many increments at a time. An atomic read-modify-write must read and write the cache line itself, with the line in an exclusive state, for each increment, so every increment that finds the line elsewhere pays a full transfer (~40–90 ns).

None of the programming assignments is about coherence directly, but its costs appear in all of them:

  • PA1–2: per-thread partial results, a thread pool’s shared counters and queues.
  • PA3: CUDA’s shared memory is a software-managed scratchpad, with no coherence at all, which is one reason GPUs scale.

Whenever several threads write data that sits close together, check for false sharing. Whenever all threads update one variable, look for a way to accumulate locally first.

Further reading

  • The Fall 2025 slides for this lecture.
  • D. J. Sorin, M. D. Hill, D. A. Wood, A Primer on Memory Consistency and Cache Coherence, 2nd ed., Morgan & Claypool, 2020 (free online). Chapters 2 and 6–8 cover SWMR, snooping and directories.
  • D. Culler, J. P. Singh, A. Gupta, Parallel Computer Architecture: A Hardware/Software Approach, ch. 5 (snooping) and ch. 8 (directories); slide 44’s line-size data comes from this book.
  • J. L. Hennessy, D. A. Patterson, Computer Architecture: A Quantitative Approach, 6th ed., §5.2–5.4.
  • W. J. Bolosky, M. L. Scott, “False Sharing and Its Effect on Shared Memory Performance”, USENIX SEDMS 1993.
  • M. Dubois, J. Skeppstedt, L. Ricciulli, K. Ramamurthy, P. Stenström, “The Detection and Elimination of Useless Misses in Multiprocessors”, ISCA 1993. It gives the precise definition of true and false sharing misses that demo 02 approximates.

Preview of Lecture 15 — Implementing synchronization + memory consistency

Coherence orders the operations on one address. Programs also care about the order of operations on different addresses: “I wrote the data, then I set the flag”. Lecture 15 shows:

  • that hardware does not keep that order by default: the store buffers we just met let a core’s later read pass its earlier write;
  • what memory consistency models (sequential consistency, TSO, the weaker ARM model) promise;
  • how fences and C++ atomics restore order;
  • how locks are built from atomic instructions, and why a good lock is careful not to cause the coherence traffic we measured today.

术语表 (Glossary, English → 中文)

English中文
cache line / tag / state bits缓存行 / 标签 / 状态位
write-back / write-through写回 / 写直达
write-allocate / write-no-allocate写分配 / 写不分配
dirty bit脏位
cold / capacity / conflict miss冷缺失 / 容量缺失 / 冲突缺失
coherence miss一致性缺失
spatial / temporal locality空间 / 时间局部性
shared address space共享地址空间
cache coherence problem缓存一致性问题
program order / serial order程序顺序 / 串行顺序
single-writer, multiple-reader (SWMR) invariant单写多读不变式
data-value invariant / write serialization数据值不变式 / 写串行化
epoch (read-write / read-only)时期(读写 / 只读)
snooping protocol / cache controller监听协议 / 缓存控制器
bus / interconnect / crossbar / ring总线 / 互连 / 交叉开关 / 环
invalidation / invalidation-based protocol失效 / 基于失效的协议
update-based protocol基于更新的协议
ownership / owner所有权 / 拥有者
MSI / MESI / MOESI / MESIF(协议名,不译)
modified / exclusive / shared / invalid已修改 / 独占 / 共享 / 无效
BusRd / BusRdX / BusWB / upgrade总线读 / 总线独占读 / 总线写回 / 升级
flush (supply dirty data)刷出(提供脏数据)
directory / home node / sharer bit vector目录 / 主节点 / 共享者位向量
point-to-point message / broadcast点对点消息 / 广播
inclusive cache包含式缓存
sparse directory / limited pointers稀疏目录 / 有限指针
NUMA (non-uniform memory access)非一致内存访问
average memory access time (AMAT)平均访存时间
inherent / artifactual communication固有 / 人为通信
true sharing / false sharing真共享 / 伪共享
padding / alignment填充 / 对齐
ping-pong (of a cache line)(缓存行)乒乓
store buffer / store-to-load forwarding存储缓冲区 / 存储到加载转发
atomic read-modify-write (fetch_add)原子读-改-写
hardware_destructive_interference_size破坏性干扰大小
local accumulation / reduction本地累加 / 归约
← 返回课程目录