Lecture 4 · Parallelizing Code: The Programming Thought Process

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

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS149 Fall 2025, Lecture 4 (Oct 2), slide deck 04_progbasics (74 slides). Slides 1–27 finish Lecture 3’s ISPC material, which these notes cover in Lecture 3 §5–§7; this file starts at slide 28. Sources: the public Fall 2025 slides; the 2023 lecture video. The grid solver example comes from D. Culler, J. P. Singh and A. Gupta, Parallel Computer Architecture: A Hardware/Software Approach (1999), as the slides say. Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro, 8 performance + 4 efficiency cores; clang 21, macOS 27). Code: code/lecture04/. Reading time: ~75 minutes for the prose; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Describe the steps of creating a parallel program — decomposition (分解), assignment (分配), orchestration (编排) and mapping (映射) — and say who (programmer, compiler, runtime, hardware) usually does each.
  2. State and use Amdahl’s law (阿姆达尔定律), and explain why a “serial” step is sometimes not inherently serial.
  3. Find the dependencies (依赖) in a loop nest, see the parallelism they allow (e.g. a wavefront (波前)), and explain how reordering a computation (red-black (红黑排序)) can expose much more.
  4. Compare blocked and interleaved assignments of data to processors by the communication they cause.
  5. Write the same computation in a data-parallel (数据并行) style and in a shared-address-space (共享地址空间) style with threads, locks (锁) and barriers (屏障), and explain what each synchronization is for.
  6. Explain a race condition (竞态条件) on x++, and compare locks, atomic operations (原子操作) and private accumulation by correctness and cost.

0.2 Prerequisites and scope

  • Prerequisites: Lectures 1–3: speedup, load imbalance, communication (Lecture 1’s three demos), threads and SIMD (Lecture 2), ISPC tasks (Lecture 3 §6.6).
  • Scope: the thought process, demonstrated on one example in two programming models. Work distribution and scheduling in depth are Lecture 5; locality and communication costs are Lecture 6; message passing, the third model for the grid solver, is Lecture 6; how locks and barriers are built is Lectures 15–16.

0.3 Section → code map

SectionIdeaDemo in code/lecture04/
§2Amdahl’s law; the two-step image example01_amdahl.py, 02_two_step_image
§5.2–§5.4dependencies, wavefronts, red-black, blocked vs. interleaved rows04_dependencies.py
§5–§6the grid solver in two models, with its locks and barriers03_grid_solver
§6.3–§6.4x++ from many threads: race, mutex, atomic, private sums05_mutual_exclusion

Run them all with cd code/lecture04 && make run (~6 seconds).

0.4 Notation

  • P = number of processors (threads, workers). T(P) = time on P processors. S = the fraction of the serial program’s work that cannot run in parallel.
  • A task (任务) is a piece of work; a worker (工作者) is whatever executes tasks: a thread, an ISPC program instance, a SIMD lane, a core.
  • As in earlier lectures, another program kept one core of the author’s machine busy during every run, which hurts 8-thread results that synchronize often. The demos detect this and say so.

1. Creating a parallel program

Slide 29 describes the thought process in three steps:

  1. Identify work that can be performed in parallel.
  2. Partition that work, and the data it uses.
  3. Manage data access, communication and synchronization.

The usual goal is to maximize speedup for a fixed computation (Lecture 1). Other goals exist, such as efficiency in cost, area or power, or solving bigger problems than fit on one machine (Lecture 6).

Slide 30 turns the steps into a pipeline. The terms are from Culler, Singh and Gupta:

problem to solve
   │  decomposition                  break it into tasks (subproblems)
   ▼
tasks ─────────── assignment ────────► workers (threads, instances, ...)
                                        │  orchestration: communication,
                                        │  synchronization, data layout
                                        ▼
                                parallel program (communicating workers)
                                        │  mapping to hardware
                                        ▼
                                execution on a parallel machine

Each responsibility may be taken by the programmer, by the system (compiler, runtime, hardware), or by both. You have already seen examples. In Lecture 2’s parallel_sinx, the programmer did everything. In ISPC’s foreach, the programmer decomposes and the compiler assigns. In ISPC tasks, a runtime assigns tasks to worker threads, and the OS maps the threads to cores.


2. Decomposition and Amdahl’s law

2.1 Decomposition

Decomposition breaks a problem into tasks that can run in parallel. As a rule, create at least enough tasks to keep every execution unit busy (Lecture 5 says how many more). The slides name the key challenge: identifying dependencies, or the lack of them. Who does it? In most cases the programmer. A compiler that parallelizes arbitrary sequential code would have to prove the absence of dependencies, including dependencies that exist only for some inputs. It works for simple loop nests; the “magic parallelizing compiler” for general code does not exist (slide 38).

2.2 Amdahl’s law

Dependencies that prevent parallel execution limit the possible speedup. Let S be the fraction of sequential execution that is inherently sequential. Then, on P processors (slides 32, 36):

                 1
speedup(P) ≤ ─────────────    and therefore   speedup ≤ 1/S  for every P.
             S + (1 − S)/P

The serial part takes S of the original time no matter how many processors there are; only the remaining 1 − S shrinks. This is an upper bound: it assumes the parallel part speeds up perfectly, with none of Lecture 1’s communication or imbalance.

01_amdahl.py tabulates it:

PS = 1%S = 5%S = 10%
87.5×5.9×4.7×
6439.3×15.4×8.8×
1,02491.2×19.6×9.9×
∞100×20×10×

With 1% serial work, 892 processors already reach 90% of the limit, at 10% efficiency. Slide 37 asks the extreme question. The Summit supercomputer had 27,648 GPUs × 5,376 ALUs = 148,635,648 ALUs. If 0.1% of an application is serial, the maximum speedup is 1,000×: 0.0007% of the machine’s potential. Big machines need programs that are almost perfectly parallel.

2.3 A simple example — and a “serial” step that isn’t

Slides 33–35 consider an N × N image processed in two steps, each taking ~N² time:

  1. multiply the brightness of every pixel by two (independent per pixel);
  2. compute the average of all pixel values.

First attempt: run step 1 in parallel (N²/P), step 2 serially (N²). Speedup = 2N²/(N²/P + N²) < 2, whatever P is.

Second attempt: step 2 computes partial sums (部分和) in parallel (each processor sums N²/P pixels), then combines the P partial sums serially. Time N²/P + N²/P + P, so speedup = 2N²/(2N²/P + P), which approaches P when N ≫ P. The “inherently sequential” running sum was a property of the algorithm, not of the problem. With P close to N², the P-step combine dominates again: the parallel algorithm’s overhead is itself a serial part (65,536 processors on a 1024² image: 32× in the model).

02_two_step_image runs both attempts on real threads with a 2048 × 2048 image. The image stays in the caches, and the threads are created once and synchronized with barriers. On this machine step 2 turned out to be 60% of the serial time, not 50%, so the demo applies Amdahl’s law with the measured S:

threadsattempt 1: measuredAmdahl boundattempt 2 (partial sums)
21.02×≤ 1.25×2.03×
41.19×≤ 1.43×3.79×
61.09×≤ 1.51×5.87×
81.03×≤ 1.54×3.18×

Attempt 2 scales close to P (until 8 threads, where the core shared with another program slows one thread, and the barrier after every step makes everyone wait for it).

Attempt 1 stays below its own bound, and the reason is instructive. Our first guess was that the serial sum got slower. It did not: it took the same 8 ms as in the serial run. The time was lost in the parallel step. With 8 threads, step 1 took 4.66 ms inside attempt 1, against 1.37 ms when run without step 2 in between. Thread 0’s sum pulls the whole image into its caches. Before the other cores can brighten their rows again, those rows must travel back to them. Amdahl’s law counts operations; the machine also charges for moving data between cores. Lectures 6 and 14 explain this cost.


3. Assignment

Assignment decides which worker does which task. Its goals are good workload balance and low communication cost. It can be static (decided before the program runs, or as soon as the amount of work and number of workers are known) or dynamic (decided as the program runs). Three examples from the slides:

  • C++ threads, static, by the programmer (slide 40): Lecture 2’s parallel_sinx gives the first half of the array to a new thread and the second half to the main thread, a blocked assignment.
  • ISPC foreach, static, by the system (slide 41): the programmer only declares the iterations independent, and the compiler assigns them to program instances. The abstraction leaves room for dynamic assignment, but current ISPC uses a static interleaved scheme (Lecture 3 §5.5 explains why).
  • ISPC tasks, dynamic, by a runtime (slide 42): launch[100] my_task(...) creates 100 tasks; the ISPC runtime keeps a pool of worker threads. After finishing a task, a worker takes the next uncompleted task from a shared list, using a “next task” pointer. Workers that get cheap tasks simply take more of them.

Lecture 1’s demo 2 showed what assignment does to load balance; Lecture 5 is entirely about it.


4. Orchestration and mapping

Orchestration (slide 43) covers everything needed to make the assigned workers cooperate:

  • structuring communication;
  • adding synchronization to preserve dependencies;
  • organizing data structures in memory;
  • scheduling tasks.

Its goals: reduce the cost of communication and synchronization, preserve locality, reduce overhead. Machine details matter here. If synchronization is expensive on a machine, a programmer will use it more sparingly.

Mapping to hardware (slide 44) assigns workers to execution units:

  • by the operating system: threads → hardware execution contexts (Lecture 2 §7.6);
  • by the compiler: ISPC program instances → SIMD lanes;
  • by the hardware: CUDA thread blocks → GPU cores (Lecture 7).

The decisions are interesting. Placing related threads on the same core can maximize locality and data sharing. Placing unrelated threads together, for example one bandwidth-bound and one compute-bound, can use the machine more efficiently.


5. A worked example: the 2D grid solver

5.1 The problem

Solve a partial differential equation on an (N+2) × (N+2) grid with an iterative method (slide 46). Each Gauss-Seidel (高斯-赛德尔) sweep replaces every interior cell by the average of itself and its four neighbours:

A[i,j] = 0.2 * (A[i,j] + A[i,j-1] + A[i-1,j] + A[i,j+1] + A[i+1,j]);

and sweeps repeat until the grid stops changing. The sequential program (slide 47):

while (!done) {
    diff = 0;
    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++) {
            prev = A[i,j];
            A[i,j] = 0.2f * (A[i,j] + A[i,j-1] + A[i-1,j] + A[i,j+1] + A[i+1,j]);
            diff += fabs(A[i,j] - prev);
        }
    if (diff / (n*n) < TOLERANCE) done = true;
}

Our demo uses n = 1024, a hot top edge (value 1) and cold other edges (0). This is the classic steady-state heat problem: heat flows in from the top.

5.2 Step 1: identify the dependencies

The update is in place. Cell (i, j) reads its left neighbour (i, j−1) and its upper neighbour (i−1, j) after they were updated in this sweep, and the other two before. So, within one sweep (slide 48), each element depends on the element to its left, and each row depends on the previous row.

Is there any parallelism? Yes (slide 49): cells on the same anti-diagonal (same i + j) do not depend on each other. A sweep can proceed as a wavefront: diagonal 1, then 2, …, then 2n − 1. 04_dependencies.py labels each cell of an 8 × 8 grid with its wavefront step:

      1  2  3  4  5  6  7  8
      2  3  4  5  6  7  8  9
      3  4  5  6  7  8  9 10
      ...
      8  9 10 11 12 13 14 15

It is real parallelism, but awkward. A 1024 × 1024 sweep needs 2047 steps, each followed by a synchronization, and the steps hold between 1 and 1024 cells (512 on average). On 64 processors the wavefront would run at 94% efficiency (ignoring synchronization costs), and on 4096 at 12.5%. Little parallelism at the start and end, and frequent synchronization: the slides call it independent work that is hard to exploit.

5.3 Change the algorithm: red-black ordering

Slide 50 takes a different route: change the order in which cells are updated, to one that is more amenable to parallelism. Colour the grid like a checkerboard (slide 51):

      R  B  R  B  R  B  R  B
      B  R  B  R  B  R  B  R
      R  B  R  B  R  B  R  B
      ...

Every neighbour of a red cell is black and vice versa. So: update all red cells in parallel; then, when they are done, update all black cells in parallel (which read the new red values). Repeat until convergence. Two steps of 524,288 independent cells each, and 2 synchronizations per sweep instead of 2047. Demo 04 computes 100% efficiency even on 4096 processors.

This changes the algorithm, not just the schedule. The new method computes different floating-point values, but it still converges to the solution, and recognizing that this is permissible takes domain knowledge of the Gauss-Seidel method. The slides call it a common technique in parallel programming. 03_grid_solver shows the difference: red-black and row-order Gauss-Seidel both stop after 244 sweeps, with grids that differ by up to 7.6·10⁻³.

An honest caveat about that stopping test. Neither grid has truly converged: heat from the top edge needs on the order of n² sweeps to cross 1024 rows. The slides’ test — the average change per cell — is passed early because most cells far from the hot edge barely change yet. Real solvers use stronger tests (e.g. the maximum change, or the residual) and much faster methods (multigrid). For this lecture’s purpose — what parallel code looks like and what it costs per sweep — it does not matter.

A bonus that the slides do not mention: red-black is faster even on one core. Row-order Gauss-Seidel takes 3.13 ms per sweep, red-black 0.63 ms. In row order every update waits for its left neighbour’s new value: a chain of a million dependent updates, which defeats instruction-level parallelism (Lecture 1). Red-black’s cells within a row are independent, so the out-of-order core overlaps them. Exposing parallelism helped every level of the machine.

5.4 Assignment: blocks or interleaved rows?

Slide 52 shows two ways to assign rows to 4 processors, in blocks of consecutive rows or interleaved (row i to processor i mod P), and asks which is better. The answer: it depends on the system the program runs on. Look at the communication each causes (slide 54). After a phase, a processor needs the new values of the cells just above and below its rows. With blocks, only the two boundary rows of each block are needed by another processor. With interleaving, every row’s neighbours belong to other processors. Demo 04 counts the cells that must be communicated per sweep (n = 1024):

Pblocked rowsinterleaved rowsratio
22,0481,048,576512×
814,3361,048,57673×
64129,0241,048,5768×

Blocked assignment requires far less communication. On a shared-memory machine “communication” means cache lines moving between cores’ caches (Lecture 6). Compare Lecture 3 §5.4: for SIMD lanes interleaving was better, because lanes share one instruction and want neighbouring data. Different workers, different best assignment.

5.5 The dependencies of the parallel program

With red-black and blocked rows, each sweep is (slide 53):

  1. all processors update their red cells in parallel;
  2. wait until all are done;
  3. (the black updates need red cells from the neighbouring blocks);
  4. update black cells in parallel;
  5. wait;
  6. (the next red phase needs black cells from the neighbours);
  7. repeat.

The waits are where orchestration comes in. The lecture now writes this program in two programming models.


6. Two ways to write the solver

6.1 Data-parallel

In the data-parallel style (slides 56–57), the program has a single logical thread of control. Parallelism comes from loops whose iterations the system may run in parallel:

while (!done) {
    for_all (red cells (i,j)) {
        float prev = A[i,j];
        A[i,j] = 0.2f * (A[i-1,j] + A[i,j-1] + A[i,j] + A[i+1,j] + A[i,j+1]);
        reduceAdd(diff, abs(A[i,j] - prev));
    }
    ... same for black cells ...
    if (diff/(n*n) < TOLERANCE) done = true;
}
  • Decomposition: each grid element is independent work (the for_all).
  • Assignment: left to the system (the slide writes ”???”).
  • Orchestration: also handled by the system. The end of a for_all block is an implicit barrier (all iterations finish before sequential control resumes), and reduceAdd is a built-in communication primitive.

The programmer writes no locks and no barriers. 03_grid_solver implements for_all in the simplest possible way: it forks P threads for each phase and joins them (the join is the implicit barrier). Each thread returns a partial sum, and the main thread adds them up (the reduceAdd). Result: 2.8× on 8 threads, correct (the grid equals the serial red-black grid bit for bit). It is the slowest correct parallel version, because it creates 7 threads twice per sweep. That is a cost of this implementation, not of the abstraction: a runtime with a persistent pool of threads (Lecture 5) would remove it without changing the program.

6.2 Shared address space with SPMD threads

In the shared-address-space style (slides 58–60), P threads all run the same solve() function (SPMD, as in ISPC). Each uses its thread id to choose its rows, and all share the grid and some global variables:

int n;  bool done = false;  float diff = 0.0;    // shared (global) variables
LOCK myLock;  BARRIER myBarrier;
float* A = allocate(n+2, n+2);

void solve(float* A) {                           // executed by ALL threads
    int threadId = getThreadId();
    int myMin = 1 + (threadId * n / NUM_PROCESSORS);
    int myMax = myMin + (n / NUM_PROCESSORS);
    while (!done) {
        float myDiff = 0.f;
        diff = 0.f;
        barrier(myBarrier, NUM_PROCESSORS);
        for (j = myMin to myMax)
            for (i = red cells in this row) {
                float prev = A[i,j];
                A[i,j] = 0.2f * (...);
                myDiff += abs(A[i,j] - prev);
            }
        lock(myLock);
        diff += myDiff;
        unlock(myLock);
        barrier(myBarrier, NUM_PROCESSORS);
        if (diff/(n*n) < TOLERANCE) done = true;  // all threads get the same answer
        barrier(myBarrier, NUM_PROCESSORS);
    }
}

Now the programmer is responsible for synchronization, using two primitives (slide 59):

  • locks, which provide mutual exclusion (互斥): only one thread in the critical section (临界区) at a time;
  • barriers: wait until all threads reach this point.

The slide asks two questions: what is the lock doing here, and why are there three barriers? §6.3–§6.6 answer them.

6.3 Communication and synchronization in a shared address space

In a shared address space, threads communicate by reading and writing shared variables (slide 62). Communication is implicit in ordinary loads and stores. The slides’ metaphor is a bulletin board that everyone can read and write. It is a natural extension of sequential programming; in fact every lecture so far has assumed it.

Shared variables need synchronization. Slide 65 shows why. Two threads each execute x++, which the processor runs as three instructions:

r1 ← x          (load the value of x into a register)
r1 ← r1 + 1     (add)
x  ← r1         (store it back)

One possible interleaving, starting from x = 0:

T1: r1 ← x        reads 0
T2: r1 ← x        reads 0
T1: r1 ← r1 + 1   1
T2: r1 ← r1 + 1   1
T1: x ← r1        stores 1
T2: x ← r1        stores 1        → x = 1, one increment lost

The three instructions must be atomic: they must happen as one indivisible step. 05_mutual_exclusion makes the race visible: 8 threads × 1,000,000 increments built from exactly these three steps.

version (8 threads)final counterlost updatesns per increment
racy load → add → store1,981,32575%0.45
lock(); x++; unlock();8,000,000017.1
atomic fetch_add8,000,000020.7
private counter, combined once8,000,00000.06

Three-quarters of the updates vanish, and the count changes from run to run. (To keep the demo legal C++, the racy version is built from separate atomic load and store operations. A plain int with a data race is undefined behaviour, and the compiler would be allowed to replace the whole loop with one x += M.)

Mechanisms for atomicity (slide 66):

  • a lock (mutex) around a critical section;
  • hardware atomic read-modify-write instructions, like atomicAdd(x, 10) / C++ fetch_add;
  • languages with first-class atomic blocks (atomic { ... }, Lectures 17–18).

Two surprises in the table. First, both correct shared versions are slower than one thread (4.3 ns with the lock, 1.75 ns with the atomic): with 8 threads, every increment needs the counter’s cache line in its own core, so the line constantly moves between cores. A critical section is serial by definition: Amdahl again. Second, on this machine the contended atomic was slower than the mutex. An instrumented run showed the mutex changing hands only every ~50 increments on average. Apple’s lock is unfair: a thread that just released it usually takes it back while the counter’s line is still in its cache. The atomic moves the line on almost every increment. Unfair locks are fast under contention, at the risk of starving other threads (Lecture 15).

6.4 Why the lock is outside the loop

Slide 68 moves the lock inside the loop, protecting diff += ... for every cell, and asks what the performance problem is. 03_grid_solver measures it: 16 ms per sweep, 0.04×, i.e. 25 times slower than one thread. A million lock acquisitions per sweep, all serialized on one lock.

The fix (slide 69), used in slide 60’s code: accumulate a private partial sum (myDiff) and add it to the shared diff once per thread per sweep. The lock is now taken P times per sweep instead of n² times. In demo 05 the same idea runs 351× faster than an atomic per increment. It is the grid-solver version of Lecture 1’s demo 1: communicate rarely.

6.5 Barriers, and why there are three

A barrier (slide 70) divides computation into phases: all computation by all threads before the barrier completes before any computation after it begins. It is a conservative way to express dependencies: everything after it is assumed to depend on everything before it.

Slide 71 asks why slide 60’s loop needs three barriers. Each prevents a specific bad interleaving:

  1. after diff = 0: otherwise a fast thread could add its myDiff to diff and a slow thread could then reset diff to 0, losing the contribution;
  2. after diff += myDiff: otherwise a thread could test diff before all contributions are in, and threads could disagree about done;
  3. after the convergence test: otherwise a fast thread could start the next sweep and reset diff = 0 while a slow thread is still reading it for this sweep’s test.

The slide shows only the red phase. With both colours, one more barrier separates red from black (§5.5), so our implementation has 4 barriers per sweep. It runs at 3.6× on 8 threads, and its grid equals the serial red-black grid exactly. Cells of one colour are independent, so their update order cannot change the result.

6.6 Trading memory for barriers

Slide 72 removes two of the barriers with a classic trick: keep three copies of diff and use them in rotation. In sweep k, threads add into diff[k % 3] and reset diff[(k+1) % 3] for the next sweep:

float diff[3];          // global diff, but now 3 copies
int index = 0;          // thread-local
diff[0] = 0.0f;
barrier(myBarrier, NUM_PROCESSORS);   // one time only: for initialization
while (true) {
    myDiff = 0.0f;
    ... compute, accumulating into myDiff ...
    lock(myLock); diff[index] += myDiff; unlock(myLock);
    diff[(index+1) % 3] = 0.0f;
    barrier(myBarrier, NUM_PROCESSORS);
    if (diff[index]/(n*n) < TOLERANCE) break;
    index = (index + 1) % 3;
}

Why three copies are enough: a fast thread may already be adding into diff[(k+1) % 3] while a slow thread still reads diff[k % 3]. These are different variables, so there is no conflict. The copy that gets reset in sweep k+1 was last read in sweep k−1, and every thread finished that test before it passed sweep k’s barrier. The slides’ summary: remove dependencies by using different variables in successive iterations; trade footprint for fewer dependencies. It is a common parallel programming technique.

Measured: 3.66× with 2 barriers per sweep (red→black plus the one before the test), against 3.63× with 4. No visible gain here: a barrier costs a few microseconds, and a sweep on 8 threads takes ~170 µs. The trick pays off when sweeps are short, with small grids or many threads; exercise 4 of the README tries it. The 3-copies version scales 1.98× on 2 threads, 3.77× on 4, 5.17× on 6 and 3.62× on 8. On the author’s machine the 8th thread shares its core with another program, and a barrier every phase makes everyone wait for it.

6.7 The two models compared

Slide 73:

data-parallelshared address space (SPMD threads)
synchronizationsingle logical thread of control; iterations of for_all may run in parallel, with an implicit barrier at the endmutual exclusion for shared variables (locks); barriers express dependencies between phases
communicationimplicit in loads and stores; built-in primitives for complex patterns (e.g. reduce)implicit in loads and stores to shared variables
who decides assignmentthe systemthe programmer (myMin, myMax)
what can go wronglittle: no explicit synchronization to get wrongraces, missing barriers, lock contention

The data-parallel program is shorter and harder to get wrong; the SPMD program gives the programmer control over assignment and synchronization, and with it the responsibility.


Summary

  • Creating a parallel program: decomposition (create independent work), assignment (give it to workers), orchestration (communication, synchronization, data layout, scheduling), mapping (workers to hardware). Programmer and system share these jobs.
  • Amdahl’s law: speedup ≤ 1/(S + (1−S)/P) < 1/S. A 1% serial part caps any machine at 100×; Summit with 0.1% serial work gets ≤ 1,000×.
  • Some serial parts are artifacts of the algorithm: a running sum becomes P partial sums plus a short combine (5.9× on 6 threads, measured). Real machines also charge for moving data between cores, which Amdahl’s law does not count.
  • The key challenge of decomposition is finding dependencies. Row-order Gauss-Seidel has only wavefront parallelism (2n − 1 synchronized steps). Red-black reordering changes the algorithm (with domain knowledge) to give two fully parallel steps per sweep, and even runs ~5× faster on one core.
  • Blocked rows communicate far less than interleaved rows (73× less on 8 processors), the opposite of the best choice for SIMD lanes.
  • Data-parallel code (for_all, reduceAdd, implicit barriers) leaves orchestration to the system. Shared-address-space code makes the programmer use locks and barriers.
  • x++ from many threads is a race: 75% of updates were lost. Locks and atomics fix correctness but serialize; contended atomics can even be slower than an unfair lock. Accumulate privately and combine once.
  • Each barrier in the solver prevents a specific bad interleaving. Three copies of diff remove two of them: trade memory for fewer dependencies.

Common pitfalls

  • Using Amdahl’s law with the fraction of code instead of the fraction of time. S is a share of the serial execution time. Measure it, as demo 02 does (60%, not the assumed 50%).
  • Concluding that a step is inherently serial because the code is a single loop. Ask whether the problem has the dependency, or only the algorithm (running sum vs. partial sums; row order vs. red-black).
  • Locking inside the innermost loop. One lock per cell made the solver 25× slower than serial.
  • Assuming an atomic is always cheaper than a lock. Under heavy contention, both are dominated by cache-line movement, and an unfair lock can win. The real cure is to synchronize less.
  • Writing x++ on a shared int “because it usually works”. It is a data race, undefined behaviour in C/C++, and it does lose updates.
  • Removing a barrier without checking which interleaving it prevented. Each barrier in slide 60 has a specific job.
  • Comparing grids or sums from different orderings with ==. Red-black and row-order Gauss-Seidel compute different floats; parallel reductions change the last digits. Compare with a tolerance, unless (like the red-black versions here) you know the order cannot matter.

Exercises

  1. Amdahl. A program spends 20 s in a serial setup and 80 s in a perfectly parallel loop. What is the speedup on 4 and on 16 processors? How many processors give 4×?

    AnswerS = 0.2. P = 4: 100/(20 + 20) = 2.5×. P = 16: 100/(20 + 5) = 4×. So 16 processors give exactly 4×, and the limit is 1/S = 5×.
  2. The image example. With N = 1024, for which P does the partial-sum version (time 2N²/P + P) run fastest? What is the speedup there?

    AnswerMinimize f(P) = 2N²/P + P: f′(P) = −2N²/P² + 1 = 0 gives P = N·√2 ≈ 1448. Then f = 2N²/1448 + 1448 ≈ 1448 + 1448 = 2896 time units, and speedup = 2N²/2896 ≈ 724×. Beyond that, the serial combine grows faster than the parallel part shrinks.
  3. Wavefront. For an n × n grid swept as a wavefront on P processors (one cell per processor per time unit, a barrier after each diagonal), show that the time is at least 2n − 1 units however large P is. What is the best possible efficiency on P = n processors?

    AnswerThe 2n − 1 diagonals must run one after another, and each takes at least one unit, so T ≥ 2n − 1. With P = n, every diagonal takes exactly 1 unit (no diagonal has more than n cells): T = 2n − 1. Efficiency = (n²/n)/(2n − 1) = n/(2n − 1) ≈ 50%.
  4. Barriers. In slide 60’s loop, remove barrier #3 (after the convergence test). Describe an interleaving of two threads that makes the program fail.

    AnswerBoth threads pass barrier #2 with diff not yet small enough. Thread A reads diff, decides "not converged", starts the next sweep and executes diff = 0, then waits at barrier #1. Thread B was slow and only now reads diff for this sweep's test: it sees 0, decides "converged" and leaves the loop. A waits at barrier #1 forever, because B will never arrive: a deadlock (and B returned a wrong answer). Barrier #3 guarantees that every thread has read diff before anyone resets it.
  5. Three copies. Why would two copies of diff not be enough in slide 72’s scheme?

    AnswerWith two copies, sweep k uses diff[k%2] and resets diff[(k+1)%2] for the next sweep. That copy is the one sweep k−1 used. A slow thread may still be reading diff[(k−1)%2] for sweep k−1's test, because the only barrier per sweep comes *before* the test. A fast thread that has passed that barrier and started sweep k would reset the copy the slow thread is reading. With three copies, the copy reset in sweep k was last read in sweep k−2, and every thread finished that read before passing sweep k−1's barrier.
  6. Private accumulation. In demo 05, the private-counter version on 8 threads still costs 0.06 ns per increment of wall time, not 0.24/8 = 0.03 ns. Where does the rest go?

    AnswerFixed costs: creating and joining 7 threads (~20 µs each, created one after another, ~0.14 ms), against only ~0.25 ms of counting per thread. The run is short enough for thread creation to matter, as in Lecture 2 §5.3.

Programming Assignment 1 practises this lecture’s ideas: decomposing a computation for threads, choosing a static assignment and explaining its load balance, and comparing ISPC’s static foreach with dynamically assigned ISPC tasks. Programming Assignment 2 (Scheduling Task Graphs on a Multi-Core CPU) asks you to build the kind of runtime that §3 and §6.1 assume: a pool of worker threads that executes tasks, first independent ones, then tasks with dependencies, using the synchronization of §6.3–§6.5. These notes do not provide solutions; Lecture 5 covers the scheduling ideas in depth.

Further reading

  • The Fall 2025 slides for this lecture and the 2023 lecture video.
  • D. E. Culler, J. P. Singh and A. Gupta, Parallel Computer Architecture: A Hardware/Software Approach, Morgan Kaufmann, 1999, chapter 2 (the source of the grid solver and of decomposition/assignment/orchestration/mapping).
  • G. M. Amdahl, “Validity of the Single Processor Approach to Achieving Large Scale Computing Capabilities”, AFIPS Spring Joint Computer Conference, 1967. The original argument.
  • J. L. Gustafson, “Reevaluating Amdahl’s Law”, CACM 31(5), 1988. Why bigger machines are used for bigger problems (Lecture 6, weak scaling).
  • Any numerical-methods text on iterative solvers (Jacobi, Gauss-Seidel, red-black ordering, multigrid), e.g. W. L. Briggs, V. E. Henson and S. F. McCormick, A Multigrid Tutorial, 2nd ed., SIAM, 2000.

Preview of Lecture 5 — Work distribution and scheduling

Today assignment was mostly static: blocks of rows decided in advance. Lecture 5 asks what to do when the work is unpredictable. It covers static, semi-static and dynamic assignment; work queues and the granularity of tasks; scheduling long tasks first; distributed queues and work stealing. Then it looks inside a real scheduler: how a fork-join runtime (Cilk) runs spawn/sync programs like parallel quicksort on a pool of threads with per-thread deques, and why it runs the child first and steals from the top.


术语表 (Glossary, English → 中文)

English中文
decomposition / assignment / orchestration / mapping分解 / 分配 / 编排 / 映射
task / worker任务 / 工作者
dependency依赖
Amdahl’s law / serial fraction阿姆达尔定律 / 串行比例
partial sum / reduction部分和 / 归约
static / dynamic assignment静态 / 动态分配
thread pool / work queue线程池 / 工作队列
Gauss-Seidel iteration / sweep高斯-赛德尔迭代 / 一轮扫描
partial differential equation (PDE)偏微分方程
convergence / tolerance收敛 / 容差
wavefront (anti-diagonal)波前(反对角线)
red-black ordering (checkerboard coloring)红黑排序(棋盘着色)
blocked / interleaved assignment分块 / 交错分配
boundary (ghost) rows边界行
data-parallel model / for_all数据并行模型 / for_all 并行循环
implicit barrier隐式屏障
shared address space共享地址空间
SPMD (single program, multiple data)单程序多数据
shared variable共享变量
race condition / data race竞态条件 / 数据竞争
lost update丢失更新
atomicity / atomic operation (read-modify-write)原子性 / 原子操作(读-改-写)
mutual exclusion / mutex / lock互斥 / 互斥锁 / 锁
critical section临界区
contention争用
unfair lock / starvation非公平锁 / 饥饿
barrier屏障
phase阶段
memory footprint内存占用
← 返回课程目录