Lecture 15 · Memory Consistency and Implementing Synchronization

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

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 15 (Nov 13), slide deck 15_consistency (60 slides; slides 3–20 review Lecture 14’s coherence material), plus slides 15–31 of deck 16_finegrainedlock (implementing locks), which these notes teach here so that Lecture 16 can focus on using locks and on lock-free code. Sources: the public Fall 2025 slides; L. Lamport, “How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs” (IEEE Trans. Computers, 1979); S. V. Adve and K. Gharachorloo, “Shared Memory Consistency Models: A Tutorial” (IEEE Computer, 1996); D. J. Sorin, M. D. Hill, D. A. Wood, A Primer on Memory Consistency and Cache Coherence (2nd ed., 2020); H.-J. Boehm and S. V. Adve, “Foundations of the C++ Concurrency Memory Model” (PLDI 2008); J. M. Mellor-Crummey and M. L. Scott, “Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors” (ACM TOCS, 1991). Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro, arm64, a weakly ordered architecture; clang 21, macOS 27). Code: code/lecture15/. Reading time: ~85 minutes for the prose; ~15 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Distinguish coherence (一致性/相干性), which orders operations on one address, from memory consistency (内存一致性模型), which orders operations on different addresses as other processors see them.
  2. Name the four program orderings (W→R, R→R, R→W, W→W). Decide which outcomes of a small “litmus test” sequential consistency (顺序一致性) allows, and prove an outcome impossible with a happens-before cycle.
  3. Explain how a write buffer (写缓冲区) hides write latency, why that breaks W→R ordering (TSO, total store order), and which further reorderings PSO and weak ordering allow.
  4. Use fences (内存屏障) and C++ atomics with memory_order (relaxed, acquire, release, seq_cst) to forbid the reorderings a program cannot tolerate. Explain why acquire/release fixes message passing but not store buffering.
  5. Define a data race (数据竞争) and state the “SC for data-race-free programs” contract. Explain why compilers, not only hardware, break racy code.
  6. Implement locks from atomic instructions: test-and-set, compare-and-swap, load-linked/store-conditional, test-and-test-and-set, ticket. Predict their latency, coherence traffic, scalability and fairness.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 14: caches, MSI, coherence traffic, store buffers in demo 03.
    • Lecture 5 and PA2: threads and locks as a user.
  • Scope: consistency models as seen by programmers and hardware designers, and lock implementations. Using locks well (fine-grained locking) and lock-free data structures are Lecture 16.

0.3 Section → code map

SectionIdeaDemo in code/lecture15/
§2–§3SC, interleavings, happens-before01_litmus_models.py Part A (uses memmodel.py)
§4write buffers, TSO01_litmus_models.py Part B
§5weaker models; what real arm64 does01_litmus_models.py Part C, 02_litmus_hw
§6data races, the compiler, ThreadSanitizer03_data_race, 03_data_race_tsan
§7lock implementations, measured04_spinlocks
§7.3lock coherence traffic05_lock_traffic.py (uses ../lecture14/coherence.py)

Run them all with cd code/lecture15 && make run (~15 seconds).

0.4 Notation

  • W_X → R_Y: a write to X followed in program order (程序顺序) by a read of Y. “Preserving” it means the write is visible to all processors before the read gets its value.
  • A litmus test (试金石测试) is a tiny multi-threaded program plus one outcome to ask about. All variables start at 0; r1, r2 are registers.
  • SB (store buffering), MP (message passing), LB (load buffering): the three classic tests.
  • RMW: an atomic read-modify-write instruction (test-and-set, compare-and-swap, fetch-and-add).

1. Coherence, in one paragraph (slides 3–20)

The first third of the deck repeats Lecture 14, so here is a one-paragraph recap:

  • Private caches replicate data.
  • A coherence protocol (MSI, MESI, snooping or directory-based) keeps the single-writer/multiple-reader and data-value invariants, so that every address has one agreed history of writes.
  • Coherence has costs the programmer sees: communication appears as longer memory latency, and false sharing makes unrelated variables in one line ping-pong between cores.

The rest of this lecture assumes coherence works perfectly, and shows that it is not enough.


2. Coherence is not consistency (slides 21–26)

Intuition says a load returns the “latest” value written. Lecture 14 made “latest” precise for one address: all processors agree on one order of the writes to X. But programs communicate through several addresses. “I wrote the data, then I set the flag” is a statement about the order of writes to two different locations. Coherence says nothing about that (slide 24): it only guarantees that each write to X eventually reaches the other processors. Memory consistency defines when a write to X becomes visible to others, relative to reads and writes of other addresses.

Slide 25 contrasts the two:

  • Coherence exists because of caches. Its goal is that the memory system behaves as if caches were not there. A machine without caches would not need it.
  • Consistency exists even without caches. It defines what any memory system, with or without caches, may let loads and stores to different addresses look like.

Who must care (slide 23)?

  • anyone who implements a synchronization library;
  • anyone who works on a kernel or a device driver;
  • anyone who writes lock-free data structures (Lecture 16).

The TL;DR of slide 26:

  • multiprocessors reorder memory operations in unintuitive ways, because that is necessary for performance;
  • application programmers rarely see it, because they use synchronization libraries;
  • systems programmers see it all the time.

3. Sequential consistency (slides 27–36)

3.1 Four orderings (slide 27)

A program’s loads and stores come in a program order. Between two operations to different addresses, there are four kinds of ordering a machine might keep:

orderingmeaning
W_X → R_Ya write must be visible before a later read gets its value
R_X → R_Ya read must get its value before a later read does
R_X → W_Ya read must get its value before a later write becomes visible
W_X → W_Ya write must be visible before a later write is

3.2 What can this program print? (slides 28–29)

initially A = B = 0
P0:  A = 1;   print B          P1:  B = 1;   print A

Sequential consistency (Lamport, 1979; slide 30) is the intuitive answer to slide 28’s question: the result is as if all operations ran in some single sequential order, each processor’s operations in program order. Slide 31 offers a metaphor: a switch that picks one processor at a time and lets it complete one memory operation. An SC machine keeps all four orderings.

Demo 01 enumerates every SC execution of the program: all 6 interleavings that keep each processor’s order.

P0 A = 1 ; P0 print B ; P1 B = 1 ; P1 print A        printed "01"
P0 A = 1 ; P1 B = 1 ; P0 print B ; P1 print A        printed "11"
...                                                    (four more give "11" or "01")
possible output: 01, 11; never "00" or "10"

Why not “00”? Slide 29 uses a happens-before graph (先行发生图), with two kinds of edges:

  • program-order edges;
  • for each read, an edge saying which write it must come before or after.

If B printed 0, P0’s print B happened before P1’s B = 1. If A printed 0, P1’s print A happened before P0’s A = 1. Together with program order, demo 01’s cycle finder prints

A = 1 → r1 = B → B = 1 → r2 = A → A = 1

This is a cycle: an event would have to happen before itself, so no sequential order produces the outcome. “10” fails the same way. Its first print returned 1, so the other processor’s second operation came after both operations of its own processor.


4. Relaxing W→R: write buffers and TSO (slides 37–46)

4.1 Why relax anything? Hiding write latency (slides 37–42)

SC is slow. Under SC, a processor that writes A must wait until the write is visible to everyone before it reads B. That can take hundreds of cycles if the write misses and must invalidate other copies, which is the coherence work of Lecture 14. Yet in slide 39’s program, A = 1 and r1 = B do not conflict: in a single-threaded program, nobody could tell if the read went first.

So every modern processor (x86, ARM, RISC-V) puts a write buffer between the core and the cache (slides 40–43). A write enters the buffer and the processor moves on immediately. The buffer drains to the cache and memory later, in order. Reads look in the processor’s own write buffer first (store-to-load forwarding), then go to the cache. The performance benefit is large (slide 42): write latency is almost fully hidden.

4.2 What the write buffer does to the program (slide 41)

Demo 01, Part B, runs the program on an operational TSO machine: per-processor FIFO write buffers that drain at arbitrary moments. It finds this execution:

T0: A = 1 -> into T0's write buffer
T0: r1 = B reads 0 from memory
T1: B = 1 -> into T1's write buffer
T1: r2 = A reads 0 from memory
   T0's buffer drains A = 1 to memory
   T1's buffer drains B = 1 to memory

r1 = r2 = 0: each processor’s read passed its own buffered write. No cache is involved. Slide 46 stresses this: coherence problems come from replicating data; consistency surprises come from reordering operations. They are different optimizations.

4.3 TSO and processor consistency (slides 43–46)

Total store order (TSO) relaxes only W→R:

  • A processor may read B before its write to A is visible to everyone; it moves its own reads ahead of its own writes.
  • Writes become visible in program order (W→W kept), and to all other processors at the same moment. Another processor cannot read the new A until all can.

Processor consistency (PC) is slightly weaker: some processors may see a write before others do.

x86 implements an (incompletely specified) form of TSO (slide 43). TSO is “slightly harder to reason about than SC”: only programs that write one variable and then read another can tell the difference.

4.4 Checking this on real hardware

Demo 02 runs SB (the program above, with registers instead of prints) 400,000 times on two cores of the author’s machine, and counts how often each outcome occurs. The variants differ in which C++ atomic operations they use:

SB variantr1 = r2 = 0 (forbidden by SC)
relaxed atomics, instructions kept in program order0.8–34% of rounds across runs
relaxed + atomic_thread_fence(seq_cst) (dmb ish) between write and read0
release store, acquire load0–0.08%
seq_cst store and load0

The “impossible” outcome is routine here: in some runs it was a third of all rounds. (Getting this measurement right took three versions of the harness; the code README explains why the first one showed 0.000%.)


5. Weaker models: reordering writes, and everything (slides 47–49)

5.1 PSO: writes may be reordered too (slides 47–48)

Partial store order (PSO) also relaxes W→W: a write buffer may let a later write (a cache hit) drain before an earlier one (a cache miss). That breaks the most common communication pattern of all, message passing:

Thread 1:  A = 1;  flag = 1;          Thread 2:  while (flag == 0);  print A;

Under PSO, thread 2 may see the flag set and still print the old A.

5.2 Weak ordering and release consistency (slide 49)

Out-of-order cores can also reorder reads (R→R) and let a later write pass an earlier read (R→W). These are all valid optimizations for a single instruction stream (slide 48). Models that allow all four reorderings include weak ordering (WO) and release consistency (RC). They give no ordering guarantees for ordinary data accesses. The motivation is performance: overlap many memory operations, execute reads as early as possible and writes as late as possible. ARM and IBM Power processors are in this family. The author’s machine is ARM.

5.3 Which outcomes each model allows

Demo 01, Part C, explores every execution of three litmus tests under each model. The “WEAK” model keeps none of the four orderings, only same-address order, fences, acquire and release. * marks the outcome SC forbids:

testSCTSOPSOWEAK
SB: A=1; r1=B ∥ B=1; r2=A01 10 1100* 01 10 1100* …00* …
SB + fences01 10 1101 10 1101 10 1101 10 11
SB + release/acquire01 10 1100* …00* …00* …
MP: data=1; flag=1 ∥ r1=flag; r2=data00 01 1100 01 1100 01 10* 1100 01 10* 11
MP + release store only00 01 1100 01 1100 01 1100 01 10* 11
MP + release store, acquire load00 01 1100 01 1100 01 1100 01 11
LB: r1=x; y=1 ∥ r2=y; x=100 01 1000 01 1000 01 1000 01 10 11*
LB + acquire loads00 01 10……00 01 10

The operational TSO machine (store buffers) and the “TSO = everything but W→R kept” description agree on every test.

Four lessons:

  1. TSO breaks only SB. Message passing works on x86 without fences, which is why code written on x86 often breaks when ported to ARM.
  2. MP’s stale read needs W→W or R→R reordering, so both the writer and the reader must be ordered. A release store with plain loads is still broken under WEAK.
  3. Release/acquire fixes MP and LB but not SB. An acquire keeps later operations after it; a release keeps earlier operations before it. Neither stops an earlier store from being passed by a later load. Only a full fence or seq_cst does.
  4. LB’s 1/1 (each read sees the other thread’s later write) needs R→W reordering, which only the weakest model allows.

And on the real arm64 machine (demo 02, 400,000 rounds each, across runs):

test, variantforbidden outcome seen in
MP, relaxed0.06–1.6% of rounds
MP, release store + relaxed loads0.03–1.2%
MP, release store + acquire load0
MP, fences on both sides0
LB, relaxed0 (allowed by ARM, never seen)

MP’s stale read appears even when the writer uses a release store. So the reader’s two loads were reordered: an out-of-order core read data before flag. LB never appeared, which illustrates the final warning of demo 02: not observing an outcome is no proof it cannot happen. Correctness must come from the model, not from testing.


6. Synchronization to the rescue (slides 50–59)

6.1 Fences (slides 50–51)

Every architecture provides instructions that make ordering stricter where a program needs it. A fence (memory barrier) waits until all memory operations before it complete before any operation after it may begin. Fences are expensive, because they drain the write buffer and stall the pipeline, so they should be used only where needed. Other primitives give ordering per operation: atomic read-modify-write instructions, acquire loads, release stores.

  • x86 (≈ TSO): lfence, sfence, mfence. In practice only mfence (or a lock-prefixed instruction) is needed, to forbid W→R.
  • ARM (weak): dmb ish (a full barrier), stlr (store-release), ldar and ldapr (load-acquire).

Demo 02 records what clang emitted for each C++ operation:

C++arm64
relaxed load / storeplain ldr / str
store(release)stlr
load(acquire)ldapr: an acquire that may complete before an earlier stlr is visible (ARMv8.3 “RCpc”)
load(seq_cst)ldar: never moves before an earlier stlr
atomic_thread_fence(seq_cst)dmb ish

The ldapr vs ldar difference is exactly the acquire/release vs seq_cst difference of §5.3, implemented in hardware. With ldapr, SB’s 0/0 appeared in a few runs. With ldar it never did.

6.2 Data races and synchronized programs (slides 52–55)

Every surprising example above has a data race:

  • two accesses to the same location from different processors;
  • at least one of them a write;
  • not ordered by synchronization (slides 52–53).

The outcome of a racy program depends on the processors’ relative speed. A program whose conflicting accesses are all ordered by synchronization (locks, barriers, fences, release/acquire) is synchronized, or data-race-free.

The key theorem (slide 54): data-race-free programs produce sequentially consistent results even on relaxed hardware. When no two unordered accesses conflict, no reordering can be observed, because every communication goes through synchronization, and synchronization enforces the needed orders. Most programs are written this way, using locks and barriers from a library. This is the deal relaxed consistency offers (slide 55):

  • hardware is free to optimize the common case, non-conflicting accesses;
  • software marks the rare conflicting ones;
  • libraries hide the details behind lock/unlock and barriers.

6.3 Languages need memory models too (slides 56–59)

Hardware is not the only reorderer. Compilers reorder, combine, hoist and delete memory operations whenever the result is the same for a single thread (slides 56–58). So a programming language must also make a contract. C11, C++11 and Java 5 all promise “SC for DRF” (slide 59):

  • if your program has no data races, it behaves sequentially consistently, and the compiler inserts whatever fences the hardware needs;
  • if it has a race, there are no guarantees at all.

Demo 03 shows how literal “no guarantees” is. The classic flag hand-off, with plain variables:

int data = 0;  bool flag = false;
producer:  data = 42;  flag = true;
consumer:  while (!flag) { }  return data;

The plan was to show the textbook failure, where the compiler hoists the load of flag out of the loop and the consumer spins forever. clang 21 did something more drastic. It compiled the consumer to two instructions:

ldr w0, [data]      ; return data
ret                 ; the wait loop is gone

C++ lets a compiler assume that a loop without side effects terminates. The loop can only terminate if flag was already true on entry, and in a race-free program nothing could change it during the loop, so the compiler deleted the loop. The consumer returned immediately with data = 0. Declaring the flag std::atomic<bool>, with a release store and an acquire load, makes the program race-free, and the consumer reads 42, guaranteed.

The same demo shows a related fact from Lecture 14: coherence makes each access consistent, but not a pair of accesses atomic. Two threads each incrementing a counter 1,000,000 times:

incrementfinal count (2,000,000 expected)
x = x + 1 on a plain int2,000,000, but only because -O2 turned each thread’s loop into a single add #1000000
atomic load, then atomic store of the value + 1~1,000,000–1,100,000 (45–49% of updates lost)
fetch_add(1)2,000,000

Only an atomic read-modify-write makes “read, add, write” indivisible.

Finding races with tools. ThreadSanitizer (-fsanitize=thread) instruments every memory access and tracks the happens-before relation between threads. Built that way (03_data_race_tsan), the program reports both races, data_plain and counter_plain, with the threads and source lines involved, whether or not the race misbehaved in that run. Use it on every multi-threaded assignment.


7. Implementing locks (deck 16, slides 15–31)

A lock must make “check that it is free, then take it” one indivisible step. Ordinary loads and stores cannot do that (that is the lost-update problem above), so every architecture provides atomic read-modify-write instructions. Each family below is a different instruction; the coherence protocol of Lecture 14 determines what each costs.

7.1 Test-and-set, compare-and-swap, LL/SC (slides 17–18, 27–31)

  • Test-and-set (slide 17): ts R0, mem[addr] atomically loads the word and stores 1. Old value 0 means you got the lock. Unlock is a plain store of 0.

  • Compare-and-swap (CAS; x86 lock cmpxchg, slide 18; CUDA atomicCAS, slide 27): “if *addr == expected, store new”, returning the old value. CAS is universal (slide 28). Any atomic fetch-and-op can be built from it with a retry loop: read the old value, compute the new one, CAS, retry if someone changed it in between. Slide 29 builds a lock this way.

    void atomic_min(int* addr, int x) {           // slide 28
        int old = *addr;
        while (atomicCAS(addr, old, min(old, x)) != old)
            old = *addr;                          // someone else changed it: retry
    }
  • Load-linked / store-conditional (LL/SC; ARM ldaxr/stxr, slide 30): a pair of instructions. LL loads a value and arms a monitor for its address; SC stores only if nobody has written the location since, and reports failure otherwise. On a cache-coherent machine, the monitor simply watches the line: an invalidation (another core’s write) or an eviction clears it. Read, modify, SC, retry gives any RMW.

  • C++11 std::atomic<T> (slide 31) wraps all of this: fetch_add, exchange, compare_exchange_strong/weak, with a memory_order on each operation (default: seq_cst). On the author’s machine clang compiles them to ARMv8.1’s single-instruction atomics (ldaddal, swpa, casa), not LL/SC loops.

What we want from a lock (slide 22):

  • low latency when it is free;
  • low interconnect traffic when many processors want it;
  • scalability;
  • low storage cost;
  • fairness, ideally first-come, first-served.

7.2 The test-and-set lock and its traffic (slides 19–21)

Every test-and-set is a write. In MSI, a write needs the line in M state, so each attempt by each waiter is a BusRdX that invalidates every other copy (slide 19). While one processor holds the lock, the waiters keep stealing the line from each other. When the holder finally releases, its store has to win the line back through that storm. Slide 21 (Culler, Singh and Gupta) shows the time per lock transfer rising steeply with the number of processors.

Test-and-test-and-set (TTAS, slides 23–25) spins with reads until the lock looks free, and only then tries the test-and-set:

void lock(int* l) {
    while (1) {
        while (*l != 0) ;                           // spin on a cached copy: hits, no traffic
        if (test_and_set(*l) == 0) return;          // looks free: now try to take it
    }
}

While the lock is held, all waiters hit in their own caches (S state), so there is no traffic. Each release invalidates every waiter’s copy. They all re-read, and race to test-and-set: O(P) traffic per release. That is O(P²) if all P processors want the lock in turn. The latency is slightly higher than plain TAS when uncontended, and there is still no fairness.

The ticket lock (slide 26) fixes fairness:

struct lock { int next_ticket; int now_serving; };
void lock(lock* l)   { int my = atomic_increment(&l->next_ticket);   // take a ticket
                       while (my != l->now_serving) ; }               // wait to be called
void unlock(lock* l) { l->now_serving++; }

One atomic per acquisition. Waiters only read. Each release causes one invalidation per waiter, and threads are served in ticket order.

Demo 05 runs these three locks on Lecture 14’s MSI simulator: P processors round-robin, each holding the lock for 8 steps. Bus transactions per acquisition:

lockP = 2P = 4P = 8P = 16
TAS42258130
TTAS5102246
ticket461018

TAS traffic grows with P × (time the lock is held). TTAS and ticket traffic grow only with P per release, and the ticket lock does the least, because it never wastes atomic attempts. Queue locks (MCS, CLH; Mellor-Crummey and Scott, 1991) have each waiter spin on its own cache line, which cuts a hand-off to O(1) transactions. They are what scalable systems use.

7.3 The locks measured on real cores

Demo 04 implements six locks with C++ atomics: TAS (exchange), the CAS lock of slide 29, an LL/SC lock in inline ldaxr/stxr assembly, TTAS, ticket, and std::mutex. T threads hammer each lock for 100 ms. Each acquisition updates 4 shared cache lines and is followed by ~100 ns of private work. Mutual exclusion is checked at the end. Ranges over four runs, nanoseconds per acquisition for all threads together:

lock1 thread8 threadsfairness at 8 (least / most acquisitions)16 threads (12 cores)
TAS49–74290–3200.66–0.78535–900
CAS loop49–53300–3800.62–0.85370–550
LL/SC49–5265–720.12–0.5068–92
TTAS49–54490–5900.11–0.51420–630
ticket49–60320–4100.95–1.004,000–280,000
std::mutex49–53133–1450.86–0.94115–140

What it shows:

  • Uncontended, every lock is cheap. The ~50 ns per round is almost all the critical section and the private work.
  • Contended, every hand-off moves lines between cores. The lock and the 4 data lines move, at ~40–90 ns each (Lecture 14’s ping-pong measurement), so 8 threads get far less throughput than 1.
  • TTAS was slower than TAS here, the opposite of slide 21. On a bus, TAS’s traffic slows everyone. On this machine’s interconnect, with only 8 cores and single-instruction atomics, TTAS’s extra step costs more than its saved traffic: a waiter must first see the release (one transfer), then win the exchange (another). The simulator’s traffic counts are right; whether they turn into time depends on the machine.
  • LL/SC was the fastest and among the least fair. The thread that just released still holds the line, so its next ldaxr/stxr succeeds without any coherence traffic: the lock stays on one core, and others starve. High throughput and fairness pull in opposite directions. The LSE swpa-based TAS lock does not show this effect, which suggests those atomics are not performed purely in the L1; that is our interpretation, not something user code can measure.
  • The ticket lock is perfectly fair, and collapses when threads outnumber cores. Its strict FIFO order means that if the next ticket holder has been descheduled by the OS, everyone waits for it, for a whole scheduler time slice. That cost 4–280 µs per acquisition in different runs.
  • std::mutex was the best fair lock. macOS’s mutex lets waiters sleep in the kernel instead of spinning, so fewer cores fight over the line, and oversubscription does not hurt it. This is the spin-vs-block trade-off of PA2’s thread pools, and why real mutexes spin briefly, then sleep.

8. Summary of the lecture (slide 60)

  • A memory consistency model defines which reorderings of memory operations hardware and compilers may perform. It is a contract between them and software.
  • Weak models are needed for performance, mainly to hide write latency with write buffers and to let out-of-order cores overlap loads. (SC can perform well too, but only with many more hardware resources for speculation.)
  • The details can be hidden in a synchronization library. That requires data-race-free programs, which the library’s primitives (locks, barriers, atomics) make easy to write.

Summary

  • Coherence orders the writes to one address. Consistency says how operations on different addresses may appear to be reordered. Caches cause coherence problems; reordering optimizations cause consistency surprises, even without caches.
  • SC keeps W→R, R→R, R→W and W→W, and allows exactly the outcomes of some interleaving of the threads. An outcome is impossible under SC exactly when its happens-before graph has a cycle.
  • Write buffers relax W→R. That model is TSO (x86): store buffering’s 0/0 appears. PSO also relaxes W→W, which breaks message passing. Weak models (ARM, Power) relax all four. On the author’s arm64 machine, SB’s 0/0 occurred in up to 34% of rounds and MP’s stale read in up to 1.6%.
  • Fences restore order. Release/acquire fixes message passing but not store buffering; seq_cst (on ARM, ldar instead of ldapr) or a full fence does. Both sides of a communication need ordering.
  • Data-race-free programs get SC semantics from C++, Java and the hardware together. Racy programs get nothing: clang deleted a plain-variable wait loop outright. Use atomics, locks and ThreadSanitizer.
  • Locks are built from atomic RMWs: test-and-set, CAS, LL/SC. TAS spins with writes and floods the interconnect; TTAS and ticket locks spin with reads; the ticket lock is FIFO-fair but collapses under oversubscription. On real 8-core hardware the throughput ranking did not follow the bus-era traffic counts, and a blocking mutex was the best fair choice.

Common pitfalls

  • “It works on my x86 laptop.” TSO forbids MP’s stale read, so missing release/acquire annotations on message-passing code show up only on ARM (phones, Apple silicon, many servers).
  • Using volatile for synchronization. In C/C++, volatile stops the compiler from removing or merging accesses, but it gives no ordering with other variables and no atomicity, and the hardware may still reorder. Use std::atomic.
  • Release/acquire for Dekker-style “set my flag, check yours”. That is the SB pattern, and it needs seq_cst or a fence between the store and the load.
  • Annotating only one side. A release store paired with a relaxed load still allows a stale read (demo 02: up to 1.2% of rounds). The reader needs acquire.
  • Concluding code is correct because a stress test never failed. LB’s outcome is allowed by ARM and never appeared in 800,000 rounds. Reason with the model, and use ThreadSanitizer.
  • Spinning with test-and-set, or FIFO spin locks under oversubscription. Spin locks assume every waiter has its own core. With more threads than cores, use a lock that can sleep.
  • Assuming a faster lock is a better lock. The LL/SC lock had 4× the throughput of TAS at 8 threads by letting one thread monopolize it. Check fairness too.

Exercises

  1. Litmus by hand. P0: x = 1; y = 1; and P1: r1 = y; r2 = x;, initially 0. List the outcomes (r1, r2) allowed under SC, TSO and a weak model. Which annotations make the weak model behave like SC?

    AnswerThis is MP. SC: (0,0), (0,1), (1,1). (1,0) is impossible, because seeing y = 1 means x = 1 was already visible. TSO: the same, since W→W and R→R are kept. Weak: (1,0) is also possible, either because the writes became visible out of order or because the reads were performed out of order. Fix: make the store of y a release and the load of y an acquire, or put a fence between the two writes *and* a fence between the two reads.
  2. A happens-before cycle. Show with a happens-before argument that SB’s outcome r1 = r2 = 0 is impossible under SC, but that r1 = 0, r2 = 1 is possible.

    Answerr1 = 0 means P0's read of B came before P1's write of B; r2 = 0 means P1's read of A came before P0's write of A. With program order (A=1 before r1=B, B=1 before r2=A) this forms the cycle A=1 → r1=B → B=1 → r2=A → A=1. For (0, 1), the order A=1, r1=B (reads 0), B=1, r2=A (reads 1) is a valid SC interleaving.
  3. Write buffers. On a TSO machine, give a step-by-step execution of SB that produces (0, 0). Then explain why adding mfence between each thread’s write and read makes it impossible.

    AnswerP0 puts A=1 in its buffer, then reads B = 0 from memory. P1 puts B=1 in its buffer and reads A = 0 from memory. Then both buffers drain. An `mfence` waits until the thread's buffer has drained, so each thread's write is visible to everyone before its own read executes. Take whichever read executes later in time. The other thread passed its fence before its own, earlier read, so the other thread's write was already visible. The later read therefore returns 1, and at least one register is 1.
  4. Dekker’s flags in C++. Two threads each do my_flag.store(true, X); if (!other_flag.load(Y)) enter_critical_section();. Is X = release, Y = acquire enough to stop both from entering? What should X and Y be?

    AnswerNo. This is SB: release/acquire does not keep an earlier store before a later load, so both loads may read false, and both threads enter. demo 02 saw this with clang's `stlr` + `ldapr`. Use `memory_order_seq_cst` for both operations, or put `atomic_thread_fence(memory_order_seq_cst)` between them.
  5. Build fetch-and-add from CAS. Write int atomic_increment(int* addr, int x) that returns the old value, using only atomicCAS(addr, compare, val), which returns the old value. Why is a retry loop necessary?

    Answer`int old = *addr; int seen; while ((seen = atomicCAS(addr, old, old + x)) != old) old = seen; return old;` Between reading `old` and the CAS, another thread may have changed `*addr`. The CAS then fails (it returns the current value), and we retry with that value. Each successful CAS corresponds to exactly one increment.
  6. Why is TTAS “potentially more efficient under contention” (slide 29)? Explain in terms of MSI states what each waiting processor does while the lock is held, for TAS and for TTAS. Then explain why demo 04 nonetheless measured TTAS slower than TAS at 8 threads.

    AnswerTAS: each attempt is a write, so it needs M state, invalidates all other copies and pulls the line to the waiter. The line ping-pongs among the waiters, and the holder's release must win it back. TTAS: waiters read; they all hold the line in S and hit locally, so there is no traffic until the release invalidates them. On demo 04's machine, the traffic TAS generates is cheap (8 cores, fast interconnect, single-instruction atomics). TTAS's release-to-acquire path needs two transfers, one to see the release and one to win the exchange, so its hand-off takes longer. Traffic matters more as P grows and bandwidth shrinks, as in slide 21.
  7. LL/SC on a coherent machine (slide 30). How might load-linked/store-conditional be implemented using the cache coherence protocol? Why can SC fail even if nobody changed the value?

    AnswerLL loads the line (typically in S or E state) and records its address in a "link register" (the exclusive monitor). Any invalidation of that line (another core's write, a BusRdX), or its eviction, clears the link. SC succeeds only if the link is still set: it upgrades the line to M and writes. Otherwise it fails without writing. Because the monitor tracks the whole line, a write to a *different* word of the same line also clears it, as does an eviction, an interrupt or a context switch. SC can therefore fail spuriously. That is why `compare_exchange_weak` may fail spuriously on LL/SC machines.
  8. Ticket-lock traffic. With P processors waiting on a ticket lock, how many bus transactions does one release cause under MSI? Compare with demo 05’s measurement at P = 16, and explain what an MCS lock changes.

    AnswerThe release writes `now_serving`, which needs M state: one BusRdX (an upgrade), invalidating P − 1 copies. Each waiter then misses once and re-reads it: P − 1 BusRds. The new holder then writes the data. That is about P + 1 transactions per hand-off, plus one for the next ticket taken; demo 05 measured 18 at P = 16. In an MCS lock, each waiter spins on a flag in its *own* queue node, and the releaser writes only its successor's flag. That invalidates one copy and causes one re-read: O(1) transactions per hand-off, independent of P.

PA2 (task-graph scheduling on a thread pool) is where this lecture’s material first bites:

  • the pool’s work queue and “tasks done” counters are shared data, which need a lock or atomics;
  • a sleeping pool needs condition variables, whose correct use relies on the mutex’s memory ordering;
  • spinning vs. sleeping workers is exactly demo 04’s ticket-lock-vs-mutex trade-off under oversubscription.

Run your PA2 code under ThreadSanitizer (-fsanitize=thread): it finds races your tests never trigger.

Further reading

  • The Fall 2025 slides for this lecture, and slides 15–31 of Lecture 16’s deck.
  • L. Lamport, “How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs”, IEEE Transactions on Computers, 1979: the definition of SC.
  • S. V. Adve, K. Gharachorloo, “Shared Memory Consistency Models: A Tutorial”, IEEE Computer, 1996.
  • D. J. Sorin, M. D. Hill, D. A. Wood, A Primer on Memory Consistency and Cache Coherence, 2nd ed., 2020, chapters 3–5 (SC, TSO, relaxed models).
  • P. Sewell et al., “x86-TSO: A Rigorous and Usable Programmer’s Model for x86 Multiprocessors”, CACM 2010; the Cambridge weak-memory pages (www.cl.cam.ac.uk/~pes20/weakmemory/), linked from slide 51.
  • ARM, “Barrier Litmus Tests and Cookbook”, linked from slide 51.
  • H.-J. Boehm, S. V. Adve, “Foundations of the C++ Concurrency Memory Model”, PLDI 2008; H.-J. Boehm, “Threads Cannot Be Implemented as a Library”, PLDI 2005.
  • J. M. Mellor-Crummey, M. L. Scott, “Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors”, ACM TOCS 1991: TTAS with backoff, ticket, MCS locks.
  • M. Herlihy, N. Shavit, The Art of Multiprocessor Programming, 2nd ed., chapters 7 (spin locks) and 3 (memory models).

Preview of Lecture 16 — Fine-grained locking and lock-free programming

Now that we can build locks, Lecture 16 asks how to use them:

  • deadlock, livelock and starvation, and the four conditions for deadlock;
  • protecting a shared linked list with one lock vs. hand-over-hand locks on each node;
  • lock-free data structures, built directly from compare-and-swap: a single-producer/single-consumer queue, a lock-free stack, and the ABA problem that breaks the naive stack, with tagged pointers and hazard pointers as fixes;
  • why lock-free code still needs the memory orderings of this lecture.

术语表 (Glossary, English → 中文)

English中文
memory consistency model内存一致性模型
coherence vs. consistency一致性(单地址) vs. 内存一致性(多地址)
program order程序顺序
W→R / R→R / R→W / W→W ordering写后读 / 读后读 / 读后写 / 写后写 顺序
sequential consistency (SC)顺序一致性
interleaving交错执行
happens-before graph / cycle先行发生图 / 环
litmus test试金石测试(石蕊测试)
store buffering (SB) / message passing (MP) / load buffering (LB)存储缓冲 / 消息传递 / 加载缓冲 测试
write buffer / store buffer写缓冲区 / 存储缓冲区
store-to-load forwarding存储到加载转发
total store order (TSO)全存储序
processor consistency (PC)处理器一致性
partial store order (PSO)部分存储序
weak ordering (WO) / release consistency (RC)弱序 / 释放一致性
multi-copy atomicity多副本原子性
memory fence / memory barrier内存栅栏 / 内存屏障
acquire / release / seq_cst / relaxed获取 / 释放 / 顺序一致 / 宽松 (内存序)
RCsc / RCpc (ldar / ldapr)顺序一致的释放一致性 / 处理器一致的释放一致性
data race数据竞争
synchronized (data-race-free) program同步程序(无数据竞争程序)
SC for DRF无数据竞争程序保证顺序一致
compiler reordering / hoisting编译器重排 / 循环外提
forward-progress assumption前向进展假设
ThreadSanitizer (TSan)线程消毒器(数据竞争检测器)
atomic read-modify-write (RMW)原子读-改-写
test-and-set (TAS)测试并设置
compare-and-swap (CAS) / cmpxchg比较并交换
load-linked / store-conditional (LL/SC)链接加载 / 条件存储
exclusive monitor独占监视器
fetch-and-add / fetch-and-op取后加 / 取后操作
spin lock自旋锁
test-and-test-and-set (TTAS)测试-测试并设置锁
ticket lock排号锁(票据锁)
queue lock (MCS, CLH)队列锁
exponential backoff指数退避
fairness / starvation公平性 / 饥饿
oversubscription超额订阅(线程多于核)
blocking (sleeping) mutex阻塞式互斥锁
← 返回课程目录