Maps to: Stanford CS149 Fall 2025, Lecture 5 (Oct 7), slide deck
05_progperf1(63 slides). The lecture opened by finishing Lecture 4’s grid solver, which these notes cover in Lecture 4 §6. Sources: the public Fall 2025 slides; the 2023 lecture video. 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). The fork-join scheduler of §4 is a small runtime written for these notes (ws_runtime.h), plus a simulator (cilk_sim.py) for the policies a library cannot switch. Code:code/lecture05/. Reading time: ~80 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:
- Explain why a small load imbalance (负载不均衡) costs a lot, and recognize when static (静态), semi-static (半静态) or dynamic (动态) assignment fits a workload.
- Implement dynamic assignment with a shared counter or work queue (工作队列), and choose a task granularity (粒度) by weighing scheduling overhead against imbalance.
- Explain why scheduling long tasks first helps, and why distributed queues with work stealing (工作窃取) scale better than one shared queue.
- Write fork-join (分叉-合并) programs with
spawn/sync(Cilk Plus), including parallel quicksort, and explain what limits their speedup (work, span, and the bound T₁/P + T∞). - Explain how a work-stealing runtime implements spawn and sync: worker pools, per-worker deques (双端队列), child-first vs. continuation-first execution, stealing from the top, and greedy join.
0.2 Prerequisites and scope
- Prerequisites: Lecture 1 (load imbalance, demo 2), Lecture 4 (decomposition, assignment, orchestration; locks and atomics).
- Scope: assigning work to workers so that all finish together, at low overhead. Communication and locality, the other half of performance tuning, are Lecture 6. Programming Assignment 2 asks you to build a task-graph scheduler; these notes explain the ideas and leave the assignment to you.
0.3 Section → code map
| Section | Idea | Demo in code/lecture05/ |
|---|---|---|
| §2.2–§2.5 | static vs. dynamic assignment; granularity | 01_static_vs_dynamic |
| §2.6 | the order of tasks in a shared queue | 02_task_order.py |
| §2.7, §3–§4 | quicksort on a work-stealing runtime; central vs. distributed queues; spawn loops | 03_work_stealing (+ ws_runtime.h) |
| §4 | child vs. continuation first, top vs. bottom, greedy vs. stalling, T₁/P + T∞ | 04_cilk_scheduling.py (+ cilk_sim.py) |
Run them all with cd code/lecture05 && make run (~8 seconds).
0.4 Notation
- P = number of workers. T₁ = the work (工作量): the time to run everything on one worker. T∞ = the span (跨度), or critical path: the time on infinitely many workers, set by the longest chain of dependent steps. Tₚ = the time on P workers.
- As in earlier lectures, another program kept one core of the author’s machine busy during the runs.
1. Programming for high performance
Slide 3 frames the next two lectures. Optimizing a parallel program is an iterative process of refining the choices of decomposition, assignment and orchestration. The key goals are at odds with each other:
- balance the workload onto the execution resources;
- reduce communication, to avoid stalls;
- reduce extra work, the overhead added to increase parallelism, manage assignment or reduce communication.
Improving one often hurts another. Smaller tasks balance better but cost more overhead (§2.5). Copying data to avoid communication costs memory (Lecture 4’s three copies of diff).
And slide 4’s tip, the most useful sentence of the day: always implement the simplest solution first, then measure performance to determine whether you need to do better. Every demo in these notes starts from the simple version and measures.
2. Balancing the workload
2.1 A little imbalance costs a lot
Ideally all processors compute all the time and finish at the same moment. Slide 5 shows why “almost” is not enough. If one of 4 processors gets twice as much work as the others, it takes twice as long. For the second half of the run the other three are idle, so 50% of the parallel program’s runtime is effectively serial. The extra work is only 1/5 of the total, yet in Amdahl’s terms S = 0.2, and the speedup is 2.5 instead of 4. Lecture 1’s demo 2 measured this; Lecture 2 found the same with heterogeneous cores.
2.2 Static assignment
Static assignment decides which worker does which work without looking at how the run goes. “Static” does not have to mean “at compile time”. The assignment may depend on run-time parameters such as the input size or the number of threads, as long as it is fixed once the run starts. Its good side: it is simple and costs essentially nothing at run time (a little index arithmetic).
When does it work (slides 7–9)?
- when the cost of each piece of work is known and equal: 12 equal tasks on 4 processors, 3 each;
- when costs are unequal but known: assign equal work instead of equal counts;
- when the statistics of the costs are predictable, e.g. the same cost on average.
01_static_vs_dynamic tests the third case. The workload is slide 11’s example: test whether each of 120,000 numbers is prime by trial division. The cost of one test is unpredictable: an even number is rejected after one step, while a prime needs ~√x/2 divisions. The numbers are x = i² + i + 41 (Euler’s polynomial, unusually rich in primes), so later elements are also more expensive on average. On 8 threads:
| assignment | speedup | busiest ÷ least busy thread |
|---|---|---|
| static, blocked (contiguous eighths) | 4.26× | 11.9 |
| static, interleaved (thread t gets t, t+8, …) | 6.70× | 1.10 |
Blocked assignment fails: the last eighth holds the biggest numbers. Interleaving works because neighbouring numbers cost about the same on average, so dealing them out like cards gives every thread a similar mix. The statistics are predictable even though individual costs are not. PA1’s first program asks you to reason about exactly this kind of choice for a different computation.
2.3 Semi-static assignment
Sometimes costs change, but slowly. Semi-static assignment (slide 10) uses the recent past to predict the near future. The application periodically profiles itself and re-adjusts the assignment, which then stays static until the next re-adjustment. Examples: an adaptive mesh that is refined as an object moves through a fluid, where parts of the mesh are reassigned to processors as it changes; or a particle simulation that redistributes particles to workers as they move. If the motion is slow, redistribution need not happen often.
2.4 Dynamic assignment
When the cost or number of tasks is unpredictable, assign work as the program runs (slide 11). The simplest version is a shared counter:
LOCK counter_lock;
int counter = 0; // shared variable
while (1) {
int i;
lock(counter_lock);
i = counter++; // or: i = atomic_incr(counter);
unlock(counter_lock);
if (i >= N) break;
is_prime[i] = test_primality(x[i]);
}
Every thread repeatedly takes the next unprocessed element. A thread that gets cheap elements simply takes more of them. The general form is a shared work queue (slide 12): worker threads pull tasks from the queue and may push new tasks as they create them.
Measured (8 threads, the same 120,000 tests):
| assignment | speedup |
|---|---|
| dynamic, locked counter, 1 element per grab | 6.39× |
| dynamic, atomic counter, 1 element per grab | 7.01× |
| dynamic, atomic counter, 4 elements per grab | 7.10× |
Every thread now finishes at the same moment (busiest ÷ least busy = 1.00), and dynamic assignment beats the best static one. A test costs 6.5 µs on average, so even a lock per element is a small price here.
2.5 What is a piece of work? Granularity
Slide 14 asks what the potential performance problem with this code is. The answer: the critical section around counter++ is serial execution (Amdahl again), and it is overhead that does not exist in the serial program. It matters when a task is cheap relative to the cost of taking it. The fix (slide 15) is to increase the granularity: take GRANULARITY elements per grab, which enters the critical section that many times less often.
The choice (slide 16) is a trade-off:
- many more tasks than processors enables good balance with dynamic assignment, which motivates small tasks;
- as few tasks as possible minimizes the overhead of managing the assignment, which motivates large tasks.
The ideal granularity depends on the workload and the machine. Demo 01 sweeps the number of elements per grab for two workloads:
| elements per grab | expensive tasks (6.5 µs each) | cheap tasks (4 ns each) |
|---|---|---|
| 1 | 7.01× | 0.05× |
| 16 | 7.09× | 0.75× |
| 256 | 7.05× | 5.01× |
| 1,024 | 6.83× | 6.57× |
| 16,384 | — | 7.18× |
| one chunk per thread | 4.14× (imbalance) | 4.65× (imbalance) |
With cheap tasks and 1 element per grab, 8 threads run 20 times slower than one. Taking an element from a counter that 8 cores hammer costs far more than testing a small number, and the counter’s cache line moves between cores on every grab (Lecture 4, demo 05). With expensive tasks, every granularity from 1 to ~1,000 works. At the far end, one chunk per thread is static blocked assignment again, with its imbalance. Too small: overhead. Too big: imbalance.
2.6 Smarter task scheduling: long tasks first
Slides 17–19 consider 16 tasks in a shared queue, one of them much longer than the rest. 02_task_order.py simulates 4 workers taking tasks in queue order, and draws the schedule (# = the long task, . = idle):
A) queue order as given -- the long task is handed out LAST:
P1 |aaaaaaeeeeeeeejjjjjjjoooooo.................................|
P2 |bbbbbbbffffffffflllmmmmmm...................................|
P3 |cccccccggggiiiiiiiiinnnn....................................|
P4 |ddddddddhhhhhhkkkkkkkkk#####################################|
makespan 19.6 (63% above the bound)
Three workers finish and wait while one runs the long task: imbalance at the very end of a dynamically scheduled computation. Two cures:
- Divide the work into more, smaller tasks (slide 18), so that the “long pole” is short relative to the whole. Splitting the long task into 4 gives a makespan of 12.1, against a lower bound of 12.0. But this may increase synchronization overhead, and it may be impossible if the long task is inherently sequential.
- Schedule long tasks first (slide 19). The worker that gets the long task does fewer tasks but about the same amount of work as the others: makespan 12.0, exactly the bound. This requires some knowledge of the workload: a prediction of which tasks are long.
With random queue orders the median makespan is 15.0. With 1,024 smaller tasks the problem fades by itself: the long-task-last schedule comes within 0.7% of the bound.
2.7 Distributed queues and stealing
One shared queue means every worker synchronizes on it for every task. Slide 20’s alternative is distributed work queues, in general one per worker:
- workers pull work from their own queue and push new work to it;
- when its local queue is empty, a worker steals work from another worker’s queue.
Most operations then touch only the worker’s own queue, so there is no contention, and synchronization is needed only for the rare steals. Demo 03 measures it on parallel quicksort (§3.4) with 8 workers:
| tasks (cutoff) | per-worker deques + stealing | one central queue |
|---|---|---|
| 217,857 (64) | 30.0 ms | 269.5 ms |
| 28,056 (512) | 25.4 ms | 54.6 ms |
| 437 (32,768) | 24.9 ms | 25.6 ms |
With large tasks the two are equal. With many small tasks the central queue is 9× slower: every push and pop fights for the same lock. With per-worker deques even 217,857 tasks cost only ~20% more than the best granularity, because almost every task is popped by the worker that pushed it.
2.8 Work with dependencies
Tasks in a queue need not be independent (slide 21). A task system can accept dependencies:
foo_handle = enqueue_task(foo); // independent of all prior tasks
bar_handle = enqueue_task(bar, foo_handle); // cannot run until foo is complete
The scheduler then manages a task graph (任务图) and assigns a task to a worker only when all its dependencies are satisfied. Programming Assignment 2 asks you to build such a system.
2.9 Summary of part 1
Slide 22: the challenge is to achieve good workload balance (all processors working all the time) at low cost: little scheduling computation and little synchronization. Static vs. dynamic is not an either/or decision but a continuum. Use what you know about the workload in advance to reduce both imbalance and task-management cost. In the limit, if the system knows everything, use a fully static assignment.
3. Fork-join parallelism
3.1 Common parallel programming patterns
Two patterns so far:
- Data parallelism (slide 24): the same operations on many data elements. It appears as OpenMP’s
#pragma omp parallel for, ISPC’sforeachandlaunch[numTasks], a higher-ordermap(foo, A, B), and CUDA’sfoo<<<numBlocks, threadsPerBlock>>>(A, B)(Lecture 7). - Explicit threads (slide 25): create one thread per execution unit, or per desired amount of concurrency, as in Lectures 1–4.
Neither fits divide-and-conquer algorithms well. In quicksort (slide 26), after partitioning, the two halves are independent problems, and each splits again. The parallelism is a tree, discovered as the program runs.
3.2 Cilk Plus: cilk_spawn and cilk_sync
The fork-join pattern expresses this naturally. The slides use Cilk Plus, a C++ extension that originated at MIT and was later supported by GCC and Intel’s compiler (slide 27):
cilk_spawn foo(args);— invokefoo, but unlike a standard function call, the caller may continue executing asynchronously withfoo. This is the fork (分叉): a new logical thread of control.cilk_sync;— returns when all calls spawned by the current function have completed. This is the join (合并).- There is an implicit
cilk_syncat the end of every function that contains acilk_spawn. So when a Cilk function returns, all work it created is complete.
Examples (slide 29):
cilk_spawn foo(); bar(); cilk_sync; // foo and bar may run in parallel
cilk_spawn foo(); cilk_spawn bar(); cilk_sync; // same parallelism, one more spawn
cilk_spawn foo(); cilk_spawn bar(); cilk_spawn fizz(); buzz(); cilk_sync;
The second line exposes the same independent work as the first, at potentially higher runtime overhead: two spawns instead of one.
Abstraction vs. implementation (slide 30). cilk_spawn does not say how or when the spawned call runs; it only says it may run concurrently with the caller. So is an implementation correct if it runs cilk_spawn foo() exactly like a normal call to foo()? Yes. That is the serial execution, and it is one legal schedule. cilk_sync, on the other hand, does constrain scheduling: all spawned calls must be complete before it returns.
3.3 Parallel quicksort
Slide 31:
void quick_sort(int* begin, int* end) {
if (begin >= end - PARALLEL_CUTOFF)
std::sort(begin, end);
else {
int* middle = partition(begin, end);
cilk_spawn quick_sort(begin, middle);
quick_sort(middle + 1, end);
}
}
Below PARALLEL_CUTOFF elements it sorts sequentially, because the overhead of a spawn would outweigh the benefit of parallelism. 03_work_stealing runs the same program on our runtime (§4), sorting 8M random integers with a cutoff of 32K:
| workers | time | speedup vs. std::sort (141 ms) |
|---|---|---|
| 1 | 148.8 ms | 0.94× |
| 2 | 76.4 ms | 1.84× |
| 4 | 40.9 ms | 3.44× |
| 8 | 24.4 ms | 5.75× |
One worker runs at 94% of std::sort, so the runtime’s overhead is small. Why only 5.75× on 8? Look at the tree. The first partition touches all 8M elements on one core (~4 ms). The next level has only 2 partitions, then 4, and so on. Along the critical path the partitions touch N + N/2 + N/4 + … ≈ 2N elements: a span of about 8 ms that no number of workers can shorten. The total work is T₁ ≈ 149 ms. A classic result for greedy schedulers (§4.8) says
T_P ≤ T_1 / P + T_∞ → 149/8 + 8 = 26.5 ms,
and we measure 24.4 ms. Quicksort with a sequential partition has limited parallelism, T₁/T∞ ≈ 19 here. Speeding it up further needs a parallel partition, built from the scan primitive of Lecture 8.
3.4 Writing fork-join programs
Slide 32’s rules of thumb:
- expose independent work (potential parallelism) to the system with
cilk_spawn; - want at least as much independent work as the machine has parallel execution capability;
- want more independent work than that, so the scheduler can balance the load. The ratio of independent work to execution capability is the parallel slack (并行松弛度); in practice ~8 is a good ratio;
- but not so much that the work becomes too fine-grained (§2.5).
4. Scheduling fork-join programs
How does a runtime implement cilk_spawn and cilk_sync? From here on the lecture is about the implementation of Cilk.
4.1 The naive implementation
Slide 33’s very simple scheduler: launch a pthread for each cilk_spawn, and turn cilk_sync into pthread_join. Potential problems:
- the spawn is heavyweight (Lecture 2: ~19 µs per thread creation on the author’s machine);
- far more concurrently running threads than cores;
- context-switching overhead;
- a larger working set than necessary, and less cache locality.
4.2 A pool of worker threads
Instead (slide 34), the Cilk runtime keeps a pool of worker threads, exactly as many as the machine has execution contexts, created once. In reality runtimes create them lazily at the first spawn, but it is fine to think of them as created at launch; ISPC does the same for tasks. Each worker runs:
while (work_exists()) {
work = get_new_work();
work.run();
}
4.3 Per-thread work queues and stealing
Consider cilk_spawn foo(); bar(); cilk_sync; (slide 35). At the spawn there are two pieces of work: the spawned child foo() and the continuation (延续), the rest of the calling function (bar() and what follows). A plain serial implementation runs the child via a normal call; the continuation is implicit in the thread’s call stack (slide 36). But while thread 0 runs foo(), an idle thread 1 could be running bar().
So each worker gets a work queue (slide 37). At cilk_spawn foo(), thread 0 places the continuation in its queue and starts executing foo(). When thread 1 goes idle (its own queue is empty), it looks in thread 0’s queue, steals the continuation into its own queue, and resumes it: it executes bar() (slides 38–40).
4.4 Run the child first, or the continuation?
At a spawn, the calling thread must decide which piece to run now and which to leave in the queue (slide 41):
- Run the child first and enqueue the continuation: other threads may steal the continuation (“continuation stealing”, 延续窃取).
- Run the continuation first and enqueue the child: other threads may steal the child (“child stealing”, 子任务窃取).
The difference shows on a spawn loop (slides 42–44):
for (int i = 0; i < N; i++)
cilk_spawn foo(i);
cilk_sync;
- Continuation first: the calling thread spawns work for all iterations before executing any. That is a breadth-first traversal of the call graph, using O(N) queue space. If nobody steals, the execution order is very different from the program without spawns.
- Child first: the caller runs
foo(0)and leaves only one stealable item, the continuation representing all remaining iterations. If nobody steals, the thread pops the continuation, spawnsfoo(1), and so on: a depth-first traversal, in the same order as the serial program. If the continuation is stolen, the thief spawns and runs the next iteration. One can prove that the queue storage for T threads is no more than T times the stack storage of the single-threaded execution.
04_cilk_scheduling.py shows both on one simulated worker (N = 1000):
child_first : first iterations run: 0, 1, 2, 3, 4, 5 ... largest deque: 1
continuation_first : first iterations run: 999, 998, 997, 996, 995 ... largest deque: 1000
Cilk chooses child first. It needs compiler support, because the compiler must package “the rest of this function” as a stealable object. A C++ library cannot do that, so library runtimes (Intel TBB, Java’s Fork/Join framework, and our ws_runtime.h) run the continuation first and let thieves steal children. Demo 03 shows the consequence on real hardware: a loop that spawns 100,000 small tasks fills the spawning worker’s deque with 98,118 entries.
4.5 Deques, and stealing from the top
Which work should a thief take (slide 45)? Look at child-first quicksort on 200 elements. Thread 0 works on elements 0–25, and its queue holds the continuations “sort 101–200”, “sort 51–100” and “sort 26–50”, oldest first. The oldest entry is the biggest piece of work.
The queue is implemented as a deque (slide 46): the owning thread pushes and pops at the bottom (tail); remote threads steal from the top (head). Slide 49 gives the reasons:
- idle threads choose a random victim to steal from;
- stealing from the top takes the largest amount of work, which reduces the number of steals;
- combined with child-first, each thread’s work has maximum locality: the owner keeps working on the newest, smallest pieces, whose data is in its cache;
- the thief and the owner do not contend for the same elements of the deque, and efficient lock-free deque implementations exist.
The simulator measures it on a deep recursion (recursive_for over 4,096 iterations, 8 workers):
| steal from | steals | utilization |
|---|---|---|
| top | 66 | 99.4% |
| bottom | 1,729 | 84.2% |
From the bottom, a thief gets the newest, smallest piece and must steal again almost at once. On quicksort the two ends barely differ (87 vs. 78 steals): with a parallelism of only ~6, there is little to steal either way.
4.6 Spawning work recursively
Slide 50 contrasts two ways to write a parallel loop:
// spawn in a loop // recursive splitting
for (int i = 0; i < N; i++) void recursive_for(int start, int end) {
cilk_spawn foo(i); while (start <= end - GRANULARITY) {
cilk_sync; int mid = (end - start) / 2;
cilk_spawn recursive_for(start, mid);
start = mid;
}
for (int i = start; i < end; i++) foo(i);
}
The recursive version generates work in parallel: the first steal takes half of the range, and its thief splits it again. The loop version generates work one iteration at a time from one place. It fills a parallel machine slowly.
Measured on the real runtime (demo 03, 100,000 tasks of ~0.13 µs, 8 workers; serial loop 13.2 ms):
| version | time | largest deque | steals |
|---|---|---|---|
| spawn loop | 30.3 ms (slower than serial!) | 98,118 | 14,543 |
| recursive_for, grain 1 | 3.5 ms | 17 | 85 |
| recursive_for, grain 64 | 2.1 ms (6.2×) | 11 | 73 |
And in the simulator, under Cilk’s child-first policy:
| program | makespan | utilization | steals | all 8 workers busy at step |
|---|---|---|---|---|
| spawn loop | 2,097 | 29.8% | 993 | never |
| recursive_for, grain 1 | 646 | 96.7% | 82 | 5 |
(ideal: 625). Child-first makes the spawn loop’s continuation the only stealable item, so it is stolen ~1,000 times, once per iteration. The loop is the natural way to write it; recursive splitting is the right way to run it. That is why parallel-for constructs in real systems split ranges recursively under the hood.
4.7 Implementing sync
What happens at cilk_sync (slides 51–61)?
- No stealing occurred: all spawned children ran on this thread, in order, so they are all finished.
cilk_syncis a no-op. This is the common case, and it costs nothing. - Stealing occurred: when a thread steals a continuation from block A, the runtime creates a descriptor for the block. It tracks how many spawns the block has made and how many have completed. Each later spawn increments the spawn count; each completion increments the done count. When the last spawned child completes (spawn = done), the block’s continuation after the sync may run.
Which thread runs it? Cilk uses greedy join scheduling (slide 62):
- all threads always try to steal when they have nothing to do; a thread goes idle only if there is no work to steal anywhere;
- the worker that initiated a spawn may not be the worker that executes the code after the
cilk_sync: whoever completes the last child continues.
The alternative, a stalling join, makes the thread that reached the sync wait for its children. The simulator compares them (child first, 8 workers):
| program | greedy join | stalling join |
|---|---|---|
| quicksort, n = 100,000 | 6,819 units (62.4% busy) | 7,303 units (58.2% busy) |
Slide 62’s reminder: the bookkeeping of steals and sync points happens only when steals occur. If large pieces are stolen, that is rare, and most of the time threads just push and pop their local deques.
Our ws_runtime.h implements sync differently. A worker waiting in sync runs other tasks (its own first, then stolen ones) until the count of unfinished children reaches zero, then continues. It is greedy in spirit (no worker idles while work exists), but the waiting function stays on that worker’s stack, and other tasks pile up on top of it. Our first version crashed exactly there: task executions nested more than the 512 KiB stacks of macOS threads could hold. Workers now get 64 MiB stacks (README). Cilk avoids the problem by design, because its sync never blocks a stack.
4.8 Work, span and the greedy bound
The slides summarize Cilk’s runtime as a locality-aware work-stealing scheduler: always run the spawned child, steal from the top, greedy join (slide 63). Behind it sits a theory (Blumofe and Leiserson, 1999) that makes the quicksort numbers of §3.3 predictable:
- work T₁: the total time of all strands of the computation;
- span T∞: the longest chain of dependent strands, the critical path;
- parallelism T₁/T∞: the maximum possible speedup;
- any greedy scheduler (one that never leaves a worker idle while work is ready) achieves Tₚ ≤ T₁/P + T∞, and a randomized work-stealing scheduler achieves this in expectation, up to a constant factor on the span term.
The simulator checks it on its quicksort model (T₁ = 34,018, T∞ = 5,774, parallelism 5.9):
| P | makespan | T₁/P + T∞ | speedup |
|---|---|---|---|
| 1 | 34,018 | 39,792 | 1.0× |
| 4 | 10,410 | 14,278 | 3.3× |
| 8 | 6,821 | 10,026 | 5.0× |
| 64 | 5,788 | 6,305 | 5.9× |
The speedup grows while P is well below the parallelism and then stops at T₁/T∞. The real quicksort of §3.3 behaves the same way. More workers cannot shorten the critical path; only a different algorithm can.
Summary
- Optimizing a parallel program trades off balance, communication and extra work. Implement the simplest version first, then measure.
- A little imbalance costs a lot: the program ends when the most loaded worker ends.
- Static assignment is free and works when costs (or their statistics) are predictable: interleaved 6.70× vs. blocked 4.26× on primality tests. Semi-static re-balances periodically. Dynamic assignment (shared counter or queue) adapts: 7.10×.
- Granularity: too small, and scheduling overhead dominates (cheap tasks with 1 element per grab ran 20× slower than serial); too large, and imbalance returns. The best size depends on the cost of a task.
- Long tasks first, or splitting them, removes the imbalance at the end of a dynamic schedule. Distributed queues with stealing avoid contention on one shared queue (30 vs. 270 ms with 218K tasks).
- Fork-join (
cilk_spawn/cilk_sync) expresses divide-and-conquer parallelism; a spawn may run in parallel, and running it as a plain call is a legal implementation. Parallel quicksort: 5.75× on 8 workers, limited by the serial partitions on its critical path, as Tₚ ≤ T₁/P + T∞ predicts. - A Cilk-style runtime keeps a pool of workers with per-worker deques: the owner works at the bottom, thieves steal from the top of a random victim (fewer, bigger steals), the child runs first (serial order, bounded space), and the join is greedy. Library runtimes run the continuation first and must be careful with spawn loops (98,118-entry deque) and stack depth.
Common pitfalls
- Assigning equal numbers of tasks instead of equal amounts of work when costs vary systematically (blocked primality tests: 4.26×).
- Picking the finest granularity “for balance” without measuring the cost of grabbing work: 0.05× with 4-ns tasks.
- Using one shared queue for many small tasks. Distribute the queues.
- Spawning N tasks in a loop. Split the range recursively, or use the system’s
parallel_for, which does so. - Expecting P× from fork-join code without computing its span. Quicksort’s sequential partition caps its parallelism at about log₂N/2.
- Assuming a spawned call runs in parallel. It only may. A program that is correct only if spawns really run concurrently is wrong (e.g. a child that waits for a value its parent sets after the spawn).
- Running deeply nested task code on small thread stacks. Default stacks of secondary threads can be small (512 KiB on macOS).
Exercises
-
Imbalance. 8 processors; 7 get 10 units of work and one gets 30. What are the speedup and the Amdahl-style serial fraction of the run? What would dynamic assignment of 1-unit tasks achieve?
Answer
Total work 100; serial time 100; parallel time 30 (the slowest), so speedup 100/30 = 3.3×, instead of 8. With 1-unit tasks taken dynamically, every processor finishes after 12 or 13 units, so the speedup is ~8× minus grabbing overhead. -
Granularity. Grabbing a task costs 50 ns (a contended atomic), each element costs 5 ns, and there are 8 workers. How many elements per grab keep the grabbing overhead below 5% of the time?
Answer
Overhead per grab ÷ work per grab = 50 / (5g) ≤ 0.05 gives g ≥ 200 elements. Demo 01's cheap-task sweep agrees: 256 per grab is the first setting above 5×, and 1,024+ approaches the best. -
Long tasks first. Tasks 7, 5, 4, 3, 3, 2 on 2 workers, taken greedily from the queue. Compute the makespan for this order and for the reverse order.
Answer
Order 7,5,4,3,3,2: W1 takes 7; W2 takes 5, then 4 (at 5, ends at 9); W1 takes 3 at 7 (ends 10); W2 takes 3 at 9 (ends 12); W1 takes 2 at 10 (ends 12). Makespan 12, which equals the bound 24/2. Reverse 2,3,3,4,5,7: W1: 2 (0–2), W2: 3 (0–3), W1: 3 (2–5), W2: 4 (3–7), W1: 5 (5–10), W2: 7 (7–14). Makespan 14. -
Child first or continuation first. On one worker, a function spawns
f(0),f(1),f(2), then syncs. Eachf(i)spawnsg(i, 0)andg(i, 1)and syncs. List the order in which the g’s run under each policy, and the largest deque.Answer
Child first: g(0,0), g(0,1), g(1,0), g(1,1), g(2,0), g(2,1), the serial order. The deque holds at most 2 continuations (the outer loop's, and f(i)'s). Continuation first: the outer function pushes f(0), f(1), f(2) (deque 3), then at the sync pops f(2) (newest first). f(2) pushes g(2,0), g(2,1) (deque 4), syncs, and pops g(2,1), then g(2,0); then f(1)'s g's in the same way, then f(0)'s. Order: g(2,1), g(2,0), g(1,1), g(1,0), g(0,1), g(0,0); largest deque 4. -
Span. Parallel mergesort splits n elements in halves recursively and merges sequentially (merge of n elements costs n). What are the work, the span and the parallelism? What changes with a parallel merge of span O(log² n)?
Answer
Work T₁ = O(n log n). Span T∞ = n + n/2 + n/4 + … = O(n), dominated by the top-level merge. Parallelism O(log n), like quicksort with a sequential partition. With a parallel merge, T∞ = O(log³ n) and the parallelism is O(n / log² n): enormous. -
Greedy bound. A program has T₁ = 1,000 ms and T∞ = 10 ms. Bound its time on 16 and on 1,000 workers. How many workers does it take before the span term exceeds the work term?
Answer
16: ≤ 62.5 + 10 = 72.5 ms (speedup ≥ 13.8). 1,000: ≤ 1 + 10 = 11 ms (speedup ≤ 100 = T₁/T∞, and ≥ 91). The terms are equal at P = T₁/T∞ = 100; beyond that the span dominates.
The related assignment: Programming Assignment 2
PA2, Scheduling Task Graphs on a Multi-Core CPU, asks you to implement the runtime this lecture describes. First a task system that runs many independent instances of a task: spawning threads per launch, then a thread pool whose idle workers spin, then one whose idle workers sleep. Then a system that accepts tasks with dependencies (§2.8) and runs them asynchronously in dependency order. Everything here applies: granularity, the cost of a shared queue, dynamic assignment. ws_runtime.h illustrates one design for fork-join programs. It is not a PA2 solution: PA2’s interface, its sleeping workers and its dependency tracking are different problems.
Further reading
- The Fall 2025 slides for this lecture and the 2023 lecture video.
- R. D. Blumofe and C. E. Leiserson, “Scheduling Multithreaded Computations by Work Stealing”, JACM 46(5), 1999. The space and time bounds behind §4.4 and §4.8.
- M. Frigo, C. E. Leiserson and K. H. Randall, “The Implementation of the Cilk-5 Multithreaded Language”, PLDI 1998. The work-first principle, child-first spawning, and the THE protocol for deques.
- D. Chase and Y. Lev, “Dynamic Circular Work-Stealing Deque”, SPAA 2005. The lock-free deque used by most modern runtimes.
- R. L. Graham, “Bounds on Multiprocessing Timing Anomalies”, SIAM J. Appl. Math., 1969. Greedy list scheduling and the longest-processing-time-first rule of §2.6.
- C. E. Leiserson, “The Cilk++ concurrency platform”, J. Supercomputing, 2010; and the OpenCilk project (opencilk.org), the maintained descendant of Cilk.
Preview of Lecture 6 — Locality and communication
Today the question was who does each piece of work. Lecture 6 asks what moves where. It covers message passing (the grid solver once more, with ghost rows and the danger of deadlock); communication that is inherent in an algorithm vs. artifactual communication caused by how data is laid out and cached; arithmetic intensity and the roofline model (a measured one for the author’s machine, continuing Lecture 3’s sweep); techniques that raise locality, such as blocking and loop fusion; and contention.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| load imbalance / load balancing | 负载不均衡 / 负载均衡 |
| static / semi-static / dynamic assignment | 静态 / 半静态 / 动态分配 |
| work queue / shared counter | 工作队列 / 共享计数器 |
| task granularity | 任务粒度 |
| scheduling overhead | 调度开销 |
| critical section | 临界区 |
| makespan | 完工时间(最后一个任务结束的时间) |
| longest-processing-time-first scheduling | 最长任务优先调度 |
| greedy list scheduling | 贪心列表调度 |
| distributed queues / work stealing | 分布式队列 / 工作窃取 |
| victim / thief | 被窃取者 / 窃取者 |
| task graph / dependency | 任务图 / 依赖 |
| divide and conquer | 分治 |
| fork-join | 分叉-合并 |
| spawn / sync | 派生 / 同步 |
| continuation | 延续(调用点之后的剩余计算) |
| child stealing / continuation stealing | 子任务窃取 / 延续窃取 |
| run child first (work-first) | 子任务优先 |
| deque (double-ended queue), top / bottom | 双端队列,顶部 / 底部 |
| worker pool / thread pool | 工作线程池 |
| parallel slack | 并行松弛度 |
| greedy join / stalling join | 贪心合并 / 停顿合并 |
| descriptor (of a sync block) | (同步块的)描述符 |
| work (T₁) / span (T∞) / parallelism | 工作量 / 跨度(关键路径) / 并行度 |
| greedy scheduler bound T_P ≤ T₁/P + T∞ | 贪心调度上界 |
| cutoff (sequential base case) | 截断阈值(串行基例) |
| stack overflow | 栈溢出 |