Lecture 24 · Thread-level parallelism

Introduction to Computer Systems · Lecture 24。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 24 (Dec 01), slide deck parallelism. Reading: CS:APP3e §12.6. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro: 12 cores = 8 performance + 4 efficiency, 128-byte cache lines, no SMT, macOS, clang 21. Timings are the best of three warm runs. Code: code/lecture24/. Reading time: ~90 minutes; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Find out what your machine is — core counts, SMT, heterogeneous cores, cache-line size — and why each number matters.
  2. Measure speedup and efficiency honestly, and recognize the benchmarking errors that produce impossible results.
  3. State Amdahl’s law, apply it, and distinguish strong from weak scaling.
  4. Explain why the same parallel code scales differently when it is bandwidth-bound versus compute-bound.
  5. Explain cache coherence and diagnose false sharing — threads that share no variable and contend anyway — and fix it with padding or registers.
  6. Explain sequential consistency, show why real hardware does not provide it, and name the correct tools (locks, atomics with ordering) instead of volatile.

0.2 Prerequisites and scope

  • Lectures 22–23: mutexes, semaphores, atomics. This lecture is about speed, where those were about correctness.
  • Lectures 9–10: the memory hierarchy, cache lines, the memory mountain. Half of this lecture is the memory system reappearing in parallel form.
  • Lecture 21: threads.
  • In scope: CS:APP §12.6 — SMP/SMT, parallel reduction, speedup and Amdahl’s law, cache coherence, false sharing, memory consistency.
  • Out of scope: GPUs, distributed memory and message passing (Lecture 25 points at them).

0.3 Section → code map

SectionIdeaDemo in code/lecture24/
§1know your machine04_machine_info.c
§2speedup, efficiency, Amdahl01_parallel_sum.c
§3what limits scaling01_parallel_sum.c (both workloads)
§4coherence and false sharing02_false_sharing.c
§5memory consistency03_memory_consistency.c

1. Know your machine

Every number in this lecture is a property of the hardware, so start by asking it. On Linux: /proc/cpuinfo, lscpu, getconf LEVEL1_DCACHE_LINESIZE. macOS has no /proc, so the equivalent is sysctl — which is what 04_machine_info.c reads:

CPU: Apple M4 Pro
  logical CPUs (hw.logicalcpu)       12
  physical cores (hw.physicalcpu)    12
  performance levels                 2
    performance cores (perflevel0)   8
    efficiency cores  (perflevel1)   4
  cache line (hw.cachelinesize)      128 bytes
  L1 data cache                      64 KB
  L2 cache                           4096 KB
  page size                          16384 bytes

Three facts from that list shape everything below.

The cores are not interchangeable. This is a heterogeneous CPU: 8 performance cores and 4 efficiency cores. “12 cores” does not mean “12×” is achievable even in principle — once the 8 fast cores are busy, extra threads land on slower ones. Expect a knee at 8.

The cache line is 128 bytes, not 64. Most textbooks (and most x86 machines) assume 64. The line is the unit of coherence and therefore the unit of false sharing (§4), so on this machine 16 longs share a line and the padding needed is twice the usual figure.

logicalcpu == physicalcpu, so there is no SMT. On a simultaneous multithreading (hyper-threading) machine — most x86 servers — logicalcpu is 2× physicalcpu: two hardware threads share one core’s functional units. Those two “CPUs” do not scale like two independent cores; they interleave on shared units, typically buying 15–30%, not 100%. A symmetric multiprocessor (SMP) means all cores are equivalent and share main memory — which is the model CS:APP assumes and which this machine, being heterogeneous, mildly violates.


2. Speedup, efficiency, and Amdahl’s law

For a program taking T1T_1 on one thread and TpT_p on pp threads:

speedup Sp=T1Tp,efficiency Ep=Spp\text{speedup } S_p = \frac{T_1}{T_p}, \qquad \text{efficiency } E_p = \frac{S_p}{p}

Efficiency is the honest number: it says what fraction of each added core you actually got. Ep=1E_p = 1 is linear speedup; anything less is overhead, contention, or a saturated resource.

Amdahl’s law bounds what parallelism can do. If a fraction α\alpha of the work is inherently serial, then even with infinitely many cores:

Sp=1α+1−αp⟶S∞=1αS_p = \frac{1}{\alpha + \frac{1-\alpha}{p}} \quad\longrightarrow\quad S_\infty = \frac{1}{\alpha}

So 5% serial work caps you at 20×, however many cores you buy — and the cap is harsh: 95% parallel code on 12 cores gives at most 1/(0.05+0.95/12)≈7.7×1/(0.05 + 0.95/12) \approx 7.7×, not 12×. The practical reading is that the serial fraction, not the core count, is usually the thing to attack.

This is strong scaling: fixed problem size, more cores. Weak scaling instead grows the problem with the cores (fixed work per core) and asks whether time stays constant — a much kinder measure, and the honest one for problems that exist because the data is large.

Measure it properly, or you will measure nonsense. The first version of this lecture’s demo reported a 9.78× speedup on 2 threads — 489% efficiency. The cause was not exotic: the first pass over a freshly written 512 MB array costs ~44 ms (page mappings, TLB fill, dirty write-back) while later passes cost ~6 ms, so the 1-thread baseline was measured cold and every multi-thread run warm. The fixes are standard — a warm-up pass before timing, and best-of-N per configuration — and both are now in the code. If a speedup exceeds your core count, suspect the measurement before believing the result.


3. What actually limits scaling

Here is the lecture’s central experiment. 01_parallel_sum.c runs the same parallel structure — split the range, accumulate privately, combine once — over two different workloads.

Workload A: memory-bound. Sum a 512 MB array. Almost no arithmetic per byte, far too large for any cache, so every element comes from DRAM.

 threads   best(ms)    speedup   efficiency
       1        6.0      1.00x         100%
       2        3.7      1.61x          81%
       4        2.9      2.07x          52%
       6        2.3      2.64x          44%
       8        2.3      2.61x          33%
      12        2.3      2.60x          22%

It stops at 2.6× and then flatlines — efficiency collapses to 22%. The bottleneck is memory bandwidth, which is a shared resource: once a couple of cores are streaming at full tilt, the rest simply queue behind DRAM. Adding cores cannot add bandwidth. This is Lecture 9’s memory mountain seen from the parallel side, and it is why so much “parallelize it” work disappoints.

Workload B: compute-bound. Real floating-point arithmetic over a 1 MB array that fits in cache, repeated.

 threads   best(ms)    speedup   efficiency
       1        4.8      1.00x         100%
       2        2.5      1.92x          96%
       4        1.3      3.77x          94%
       6        0.9      5.50x          92%
       7        0.8      6.21x          89%
       8        0.9      5.56x          70%   <-- the knee
      12        0.9      5.69x          47%

Near-linear to 7 threads at 89–96% efficiency, then a distinct knee at 8, where efficiency falls from 89% to 70%. That knee is not mysterious: §1 told us this machine has exactly 8 performance cores. Threads beyond that run on efficiency cores and contribute less.

Same code, same parallelism, 2.6× versus 6.2×. The difference is entirely which resource saturates first. The engineering lesson: before parallelizing, find out whether you are bandwidth-bound (then parallelism will not help much — improve locality instead, Lecture 10) or compute-bound (then it will, up to your real core count).

3.1 Never synchronize per element

The demo also makes the Lecture 22 point concretely: a mutex or an atomic on every element turns a memory-bound loop into a contention-bound one — measured at roughly 46× and 17× the cost of a plain add respectively. The right structure for any reduction is private accumulator per thread, combined once. Which leads directly to the next section, because that structure has a trap.


4. Cache coherence and false sharing

4.1 Coherence

Each core has its own cache, so the same memory could sit in several caches at once. Cache coherence is the hardware protocol that keeps those copies consistent. The usual scheme (MESI) gives every cached line one of four states — Modified, Exclusive, Shared, Invalid — with one rule that matters here:

To write a line, a core must hold it exclusively, which means invalidating every other core’s copy first.

Reads can be shared freely; writes cannot. So two cores writing the same line must take turns owning it, and the line is transferred between caches on every alternation.

4.2 False sharing, measured

Now take Lecture 22’s advice — “give each thread its own variable” — and do it the obvious way:

long counter[NTHREADS];          /* thread i touches counter[i] only */

No thread ever reads or writes another’s element. No race, no lock, always the right answer. And it is 2.79× slower than it needs to be. 02_false_sharing.c, 8 threads × 20 M increments of their own counter:

layouttimevs packed
A: long counter[8] (packed — one line)54 ms1.00×
B: padded to 128 bytes each19 ms2.79× faster
C: register-local, one store at the end7 ms7.97× faster

All three compute the correct per-thread totals. The only difference between A and B is where the counters sit in memory.

The cause: eight adjacent longs all fit inside one 128-byte line, so all eight threads are writing the same line. By §4.1 each write requires exclusive ownership, so the line ping-pongs between the eight cores’ caches — roughly one coherence transfer per increment. The threads are logically independent and physically serialized.

This is false sharing: the sharing is an artefact of memory layout, not of program logic. The fixes:

  • Padding — give each value its own cache line (struct { long v; char pad[120]; }, or alignas(128)). Layout B.
  • Better: keep it in a register and store once at the end. Layout C, and 8× faster than packed, because there is no repeated memory traffic to be coherent about.

The moral is a sharpening of Lecture 22’s: “each thread has its own variable” is not enough — each thread needs its own cache line. This is why real concurrent code is littered with alignas(64)/alignas(128) and pad[] fields, and why getting the line size right matters (128 here, not the textbook’s 64; padding to 64 would have fixed it only partially).

False sharing is also the explanation for Lecture 22’s strangest measurement — a shared counter getting slower with more threads (atomic 2.4 → 12.0 ns/op). That was true sharing of one variable; this is false sharing of one line. The mechanism is identical.


5. Memory consistency: when your reasoning stops being valid

5.1 The question

Coherence is about one location. Consistency is about the order in which writes to different locations become visible. Consider two threads, X and Y both initially 0:

thread 1:  X = 1;  r1 = Y;          thread 2:  Y = 1;  r2 = X;

Enumerate every interleaving of those four operations. You will find (r1,r2) can be (0,1), (1,0) or (1,1) — but never (0,0). For (0,0), thread 1 must read Y before thread 2 wrote it and thread 2 must read X before thread 1 wrote it, which no single sequential order permits.

The model that reasoning uses is sequential consistency (SC): all cores see one global order of all memory operations, consistent with each program’s own order. It is what your intuition assumes. Real hardware does not provide it.

5.2 The measurement

03_memory_consistency.c runs that litmus test 200 000 times:

== without any memory barrier ==
    (r1,r2) = (1,1):        0
    (r1,r2) = (0,1):      251
    (r1,r2) = (1,0):      194
    (r1,r2) = (0,0):   199555   <-- impossible under sequential consistency

== with a seq_cst memory fence between the store and the load ==
    (r1,r2) = (0,0):        0

The “impossible” outcome happened 99.78% of the time. Not a rare curiosity — the normal case. And a single atomic_thread_fence(memory_order_seq_cst) between each store and load eliminated it entirely (0 of 200 000), at a cost of 100 ms → 177 ms.

Why: a core may put its store in a store buffer and let a subsequent load proceed before that store is visible to anyone else. Both threads do exactly that, so both read the other’s stale 0. Nothing is broken; the architecture permits it.

How much it permits varies:

  • x86-64 uses TSO (total store order): only store→load reordering is allowed, so this anomaly exists but is rarer.
  • arm64 (and POWER) are deliberately weaker — more reordering is permitted, in exchange for simpler, faster hardware. Which is why this machine shows the anomaly so readily.

A memory barrier (fence) forbids reordering across itself, restoring the ordering your reasoning assumed, at a cost.

5.3 What to do about it

Three conclusions, in order of importance:

  1. Do not write your own synchronization out of plain loads and stores. Every lock-free algorithm you have seen in a textbook assumes a memory model; getting it wrong produces bugs that appear only on some architectures, under some loads. Use mutexes, semaphores, or atomics with explicit ordering — they emit the correct barriers for the platform.
  2. volatile is not synchronization. It stops the compiler caching a value in a register; it emits no barrier, so the hardware may still reorder, and it provides no atomicity (Lecture 22). It is for device registers and signal-handler flags, nothing more. The demo uses volatile precisely to show that it does not help.
  3. C11 atomics let you choose. memory_order_seq_cst (the default) is the safe, intuitive, slower option; acquire/release are the cheaper idioms for lock-like handoffs; relaxed gives atomicity with no ordering and should be reserved for counters you only read at the end.

A caveat on the 99.78%. The two threads are released from a barrier each round, which tightly aligns their store/load pairs and maximizes the reordering window. That is exactly what a litmus test is for, but it means the figure measures “how often when maximally provoked”, not “how often in ordinary code”. The number you should take away is not 99.78% — it is that the outcome is permitted, so correctness must never depend on its absence.


Summary

  • Know your machine. This one: 12 cores but 8 performance + 4 efficiency (so 12× is impossible in principle), 128-byte cache lines (not 64), no SMT. On Linux read /proc/cpuinfo; on macOS, sysctl.
  • Speedup Sp=T1/TpS_p=T_1/T_p, efficiency Sp/pS_p/p. Amdahl’s law: a serial fraction α\alpha caps speedup at 1/α1/\alpha, so 5% serial means at most 20× ever. Strong scaling fixes the problem size; weak scaling grows it with the cores.
  • Measure honestly. A cold baseline against warm runs produced a fake 9.78× on 2 threads. Warm up, and take the best of several runs. A speedup above the core count means a broken measurement.
  • What limits scaling is whichever resource saturates first. Identical parallel code scaled 2.6× when memory-bandwidth-bound (efficiency 22%) and 6.2× when compute-bound (efficiency 89%), with a visible knee at 8 threads = the performance-core count. Adding cores cannot add bandwidth.
  • Never synchronize per element; use a private accumulator per thread and combine once (a per-element mutex cost ~46× a plain add).
  • Cache coherence requires exclusive ownership of a line to write it. False sharing therefore makes threads that share no variable contend over a shared line: measured 2.79× slower packed than padded, and 7.97× slower than register-local. Each thread needs its own cache line, not merely its own variable.
  • Sequential consistency is not what hardware provides. The “impossible” (0,0) outcome occurred in 99.78% of rounds on arm64, and a seq_cst fence removed it completely. Use locks or ordered atomics; volatile is not synchronization.

Common pitfalls

  • Benchmarking a cold baseline against warm runs — the fastest route to an imaginary speedup.
  • Believing a superlinear speedup. Occasionally real (more aggregate cache), usually a measurement bug.
  • Assuming n cores means n×. Amdahl, bandwidth, SMT and heterogeneous cores each cap it independently.
  • Parallelizing a bandwidth-bound loop. Improve locality first (Lecture 10); cores cannot add bandwidth.
  • Synchronizing per element instead of per thread.
  • Giving each thread its own variable but not its own cache line — false sharing, with no symptom except slowness.
  • Padding to 64 bytes on a 128-byte-line machine. Read the line size; do not assume it.
  • Writing lock-free code against your intuition instead of a memory model.
  • Using volatile for inter-thread ordering. It is neither atomic nor ordered.
  • Treating “I could not reproduce the reordering” as proof it cannot happen. It is permitted; that is enough to forbid relying on it.
  • Measuring only total time. Efficiency is what tells you whether the last four cores did anything.

Exercises

  1. Amdahl. A program is 90% parallelizable. What is the best speedup on 8 cores, and on infinitely many?

    Answer$S_8 = 1/(0.1 + 0.9/8) = 1/0.2125 ≈ \mathbf{4.7×}$ — not 8×, despite 90% being parallel. As $p→∞$, $S_∞ = 1/0.1 = \mathbf{10×}$. Doubling the cores past this point buys very little; reducing the 10% serial fraction is the only path to more.
  2. Which limit? Workload A scaled 2.6× and workload B 6.2× on the same machine with the same thread code. Explain, and say what you would do to speed up A.

    AnswerA is **memory-bandwidth-bound** (512 MB streamed, trivial arithmetic): bandwidth is shared, so extra cores queue behind DRAM. B is **compute-bound** and cache-resident, so cores are the limit and it scales until it runs out of performance cores. To speed up A, attack the *memory traffic*, not the thread count: improve locality/blocking (Lecture 10), use a smaller data type, or fuse passes so each byte is read once.
  3. The knee. Why does workload B’s efficiency drop from 89% at 7 threads to 70% at 8, then keep falling?

    AnswerThe machine has only **8 performance cores**. Up to ~7 threads each gets a fast core (plus one left for the OS and the main thread). Beyond 8, threads are placed on the 4 **efficiency** cores, which execute the same work more slowly; since the work was split evenly, the whole result waits on the slowest piece. Heterogeneous cores make even-sized partitioning the wrong strategy.
  4. False sharing. Two threads increment long c[2] (c[0] and c[1]). There is no race. Why can this be slower than using two variables 128 bytes apart, and how much slower was it here?

    Answer`c[0]` and `c[1]` share one 128-byte cache line. A core must own a line **exclusively** to write it, so the line is invalidated and transferred between the two cores on essentially every increment. Measured with 8 threads: **54 ms packed vs 19 ms padded, 2.79×**. The fix is padding each counter to its own line, or better, accumulating in a register and storing once (7 ms).
  5. (0,0). Explain how r1 == 0 && r2 == 0 can happen for X=1;r1=Y / Y=1;r2=X, and what single addition prevents it.

    AnswerEach core places its store in a **store buffer** and allows its subsequent **load** to execute before that store becomes visible to the other core. So both loads read the initial 0. No interleaving of the four operations explains it — the operations are not globally ordered. A **memory barrier** (`atomic_thread_fence(memory_order_seq_cst)`) between each store and load forbids that store→load reordering; measured, it took the count from 199 555 to **0**.
  6. volatile. A colleague makes both X and Y volatile and declares the race fixed. What is right and wrong about that?

    AnswerRight: `volatile` stops the **compiler** from caching the values in registers or eliding the accesses, so each read really reads memory. Wrong: it emits **no memory barrier**, so the **hardware** may still reorder the store and the load — the demo uses `volatile` and still shows `(0,0)` 99.78% of the time — and it provides no atomicity for read-modify-write. Use atomics or a lock.
  7. SMT. A machine reports 8 physical and 16 logical CPUs. Should you expect 16× on a compute-bound workload?

    AnswerNo. The 16 "CPUs" are 8 cores with **2 hardware threads each**, sharing each core's functional units, caches and bandwidth. SMT helps when threads stall (cache misses leave the units idle for a partner to use), typically buying **15–30%**, not 100%. For a compute-bound workload that already keeps the units busy, the second thread per core adds little and can even hurt by halving the effective per-thread cache.

No lab is tied to this lecture; its content is what makes the earlier labs’ performance work make sense — cachelab’s locality (Lecture 10) is the single-threaded version of §3’s bandwidth limit, and any concurrent server benefits from §4’s padding. Per the course’s academic-integrity policy these notes contain no lab solutions.

Further reading

  • CS:APP3e §12.6 (parallelism, Amdahl, coherence, consistency) and practice problems 12.21–12.25.
  • Ulrich Drepper, What Every Programmer Should Know About Memory — the definitive long-form treatment of coherence and false sharing.
  • Paul McKenney’s Is Parallel Programming Hard? and the Linux kernel’s memory-barriers.txt for memory models in earnest.
  • The “litmus test” literature (Sewell, Alglave et al. on x86-TSO and ARM) — formal models of exactly §5’s experiment.
  • perf (Linux) or Instruments (macOS) to see coherence misses directly rather than inferring them from timings.

Preview of Lecture 25: Frontiers of computing

The course ends by looking outward. Lecture 25 traces where these ideas go next — multicore and accelerators (GPUs, TPUs), the memory wall and new memory technologies, the end of Dennard scaling and the turn to specialization, security as a first-class systems concern (Spectre/Meltdown as abstraction leaks of exactly the kind this course has been studying), and warehouse-scale computing. It closes by revisiting the five realities from Lecture 1 and pointing at the courses that continue each thread.


术语表 (Glossary, English → 中文)

English中文
thread-level parallelism线程级并行
SMP (symmetric multiprocessor)对称多处理器
SMT / hyper-threading同时多线程 / 超线程
heterogeneous cores异构核心
performance core / efficiency core性能核 / 能效核
logical / physical CPU逻辑 / 物理 CPU
sysctl / /proc/cpuinfo查询机器信息
speedup加速比
efficiency并行效率
Amdahl’s law阿姆达尔定律
serial fraction串行比例
strong / weak scaling强 / 弱扩展
superlinear speedup超线性加速
warm-up (benchmarking)预热
embarrassingly parallel易并行
reduction归约
private accumulator私有累加器
memory bandwidth内存带宽
bandwidth-bound / compute-bound带宽受限 / 计算受限
saturation饱和
cache coherence缓存一致性
MESI protocolMESI 协议
exclusive ownership独占所有权
invalidation失效
cache line缓存行
false sharing伪共享
padding / alignas填充 / 对齐
memory consistency内存一致性
sequential consistency顺序一致性
TSO (total store order)全存储序
weak memory model弱内存模型
store buffer存储缓冲区
memory reordering内存重排序
memory barrier / fence内存屏障
memory_order_seq_cst / acquire / release / relaxed内存序
litmus test石蕊测试(内存模型)
volatile (not synchronization)易变(不是同步)
← 返回课程目录