Parallel Fibonacci of 6 has 49 small pieces of work, but its longest chain is only 12 pieces long. No machine can beat 12 steps, and a simple greedy scheduler on 4 cores already finishes in 15.
Pick n, drag the number of processors and press Play. Watch the cores fill the chart, and watch where adding cores stops helping. Then we build, piece by piece, spawn and sync, work and span, the greedy bound, races, and parallel matrix multiply and merge sort.
You need a little Python and recursion. Divide and conquer helps but is not required. We build the rest from zero.
Based on Chapter 27, Multithreaded Algorithms, of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. Previous: Maximum Flow. Next: Matrix Operations.
Each circle is a strand and costs one time step. The warm path is the critical path. The scheduler is greedy: at each step it runs up to P ready strands, the oldest first. The strand counts follow the CLRS model of P-FIB; the tie-break rule is ours.
Chapter 0
Add sixteen numbers two ways and see why the shape of the work decides the speed
Your laptop has 8 cores. You must add 16 numbers. A plain loop adds them one after another: 15 additions, 15 time steps, and one core does all of it. The other seven cores wait.
Now pair the numbers. Add 8 pairs at the same time, then 4 pairs of sums, then 2, then 1. That is the same 15 additions, but 8 cores finish in 4 steps.
The tree adds pairs. The number in each addition is the step in which it runs. Drag the number of processors.
Illustrative: one addition costs one time step. At each step the processors take as many ready additions as they can.
Two numbers explain both bars. Both plans do 15 additions in total. But the loop is one chain of 15 additions, each waiting for the one before. The tree's longest chain is 4. Past 8 processors the tree stops getting faster, because no chain can run faster than one addition per step.
CLRS studies this with dynamic multithreading. You mark which work may run in parallel. A scheduler, the runtime that hands ready work to idle processors, decides who runs what. You use three keywords: spawn, sync and parallel for. Delete them and you get the serialization, a correct serial program.
The failure. Symptom: a program on 8 cores runs no faster than on 1. Measure: time it with 1 worker and with 8; a ratio near 1 means the work is one long chain. Fix: change the algorithm so the longest chain is short, like the tree.
Chapter 1
Cut a parallel program into strands and draw who waits for whom
The smallest parallel program in CLRS computes Fibonacci numbers. It is slow on purpose: it shows the structure with nothing else in the way.
pseudocodeP-FIB(n): if n <= 1: return n x = spawn P-FIB(n - 1) # the child MAY run in parallel y = P-FIB(n - 2) # the parent keeps going sync # wait for every child of this call return x + y
spawn lets the child call run in parallel with the lines after it. sync waits until every child this call spawned has returned. Without the sync, the parent could read x before the child writes it.
A strand is a run of instructions with no spawn, sync or return inside it. Each call with n ≥ 2 has three strands. A runs up to the spawn. B makes the call P-FIB(n − 2). C runs after the sync. A base case is one strand.
The strands and their order form the computation DAG, a directed graph with no cycles. A strand can run only after every strand that points to it finishes.
| Edge | From | To |
|---|---|---|
| Spawn | strand A | the first strand of the spawned child |
| Call | strand B | the first strand of the called child |
| Return | the last strand of a child | strand C of its parent |
| Continuation | A, then B | B, then C, in the same call |
Each row is one level of calls. Pick n, then pick an edge kind to light it.
The layout follows CLRS Figure 27.2: spawn and call edges point down, return edges point up, continuation edges point right.
Count P-FIB(4). Four calls have n ≥ 2: P-FIB(4), P-FIB(3) and two P-FIB(2). That gives 4 × 3 = 12 strands. Five calls are base cases, one strand each. The DAG has 12 + 5 = 17 strands and 4 + 4 + 8 + 8 = 24 edges.
The failure. Symptom: P-FIB returns a wrong sum now and then. Measure: run the serialization; if it is always right, the parallel version reads a value too early. Fix: put a sync between the spawn and the first use of its result.
Chapter 2
Measure a DAG with two numbers and get two floors that no machine can break
Give every strand a cost of one time step. Two numbers then describe the whole DAG. The work, called T1, is the number of strands: the time on one processor. The span, called T∞, is the number of strands on the longest path: the time with as many processors as you like. The longest path is the critical path.
Now call the time on P processors TP. In one step, P processors run at most P strands. And the strands on one path must run one after another. Both facts give a floor.
T-P is at least the larger of T-one over P and T-infinity.
Divide the work T-one by P. Take the span T-infinity. Whichever is larger, no schedule on P processors finishes sooner.
P-FIB(6): T-one = 49, T-infinity = 12. On P = 4: 49 / 4 = 12.25 and 12, so T-P is at least 12.25, which means 13 whole steps. The hero's greedy run takes 15.
The ratio T1/T∞ is the parallelism: the most speedup the DAG allows, and so the most processors worth buying.
How do you get the span of a program? Two pieces in series: add their spans. Two pieces in parallel: take the larger span. In P-FIB the spawned child and the call run in parallel, so the span takes a max. Call the span of P-FIB(n) T∞(n).
T-infinity of n equals the larger of T-infinity of n minus one and T-infinity of n minus two, plus theta of one.
The span of n is the span of the slower child, n minus one, plus a constant. So each level of n adds a constant, and the span grows like n. The work adds both children and grows like the Fibonacci numbers themselves.
Counting strands: T-infinity(2) = 4, then each level adds 2, so T-infinity(4) = 8 and T-infinity(30) = 60. The work of P-FIB(30) is 5,385,073 strands. Parallelism = 5,385,073 / 60, about 89,751.
Blue is the work, warm is the span, on a log scale. Drag n.
Exact strand counts in the CLRS model: work W(n) = W(n − 1) + W(n − 2) + 3, with W(0) = W(1) = 1.
The failure. Symptom: P-FIB(4) on 8 cores is barely faster than on 2. Measure: its parallelism is 17 / 8, about 2.1. Fix: no scheduler can do better; give the cores a bigger input.
Chapter 3
Never leave a core idle while work is ready, and land within twice the best schedule
A strand is ready when every strand that points to it has finished. A greedy scheduler follows one rule: at each step, run as many ready strands as it can, up to P. It does not plan ahead. It does not care which ready strands it picks.
Each step is one of two kinds. In a complete step, at least P strands are ready, so all P processors work. In an incomplete step, fewer than P are ready, so the scheduler runs all of them and some processors idle.
Each column is one step, each row one processor. Blue marks a complete step, warm an incomplete one. Drag P, then Step or Play.
The DAG is P-FIB(6): work 49, span 12. Ties go to the strand that became ready first.
Now count. Every complete step does P strands of work, and there are only T1 strands, so there are at most T1/P complete steps. An incomplete step runs every ready strand. That includes the first strand of every longest remaining path, so the longest remaining path gets one strand shorter. So there are at most T∞ incomplete steps.
T-P is at most T-one over P plus T-infinity.
Every step is complete or incomplete. Add the most complete steps, T-one over P, to the most incomplete steps, T-infinity. A greedy run never takes longer. This is CLRS Theorem 27.1.
P-FIB(6) on P = 4: 49 / 4 + 12 = 24.25. The run takes 15 steps: 10 complete (limit 12.25) and 5 incomplete (limit 12).
How good is that? Each of T1/P and T∞ is at most max(T1/P, T∞), so their sum is at most twice the floor from Chapter 2. No schedule beats the floor. So a greedy schedule is never more than 2 times slower than the best one.
Real runtimes have no central list of ready strands. In work stealing, each processor keeps its own queue of spawned work. An idle processor takes the oldest item from a random other processor's queue. Blumofe and Leiserson proved that this runs in expected time T1/P + O(T∞), the same shape as the greedy bound.
The failure. Symptom: adding cores makes a program slower. Measure: time spent waiting for one shared task queue. Fix: give each core its own queue and let idle cores steal.
Chapter 4
Read how much faster P cores can go, and see why a test machine can lie
The speedup on P processors is T1/TP: how many times faster than one processor. Both laws from Chapter 2 cap it.
T-one over T-P is at most the smaller of P and T-one over T-infinity.
The speedup can never pass the number of processors P. It can never pass the parallelism, T-one over T-infinity. Take the smaller cap.
P-FIB(6) on P = 4: the caps are 4 and 49 / 12, about 4.08, so at most 4. The greedy run gets 49 / 15, about 3.27.
Speedup equal to P is perfect linear speedup. The ratio of parallelism to P is the slackness. Below 1, perfect speedup is impossible. Well above 1, T1/P dominates the greedy bound, and speedup comes close to P. A common rule of thumb asks for slackness of about 10.
CLRS tells a story from a chess program at MIT. The team tested on 32 processors and planned to run on 512. One change cut the work from 2,048 to 1,024 but raised the span from 1 to 8. Estimate each run with T1/P + T∞.
Grey is the original, teal the "optimized" version. Drag P and watch the curves cross.
The numbers are the simplified ones from CLRS Section 27.1. We estimate time as T1/P + T∞.
On 32 processors the change wins: 40 steps against 65. On 512 it loses: 10 against 5. Its parallelism fell from 2,048 to 128, and 512 cores need more than 128.
A related cap is Amdahl's law. Suppose a fraction s of the work must run serially, and the rest splits perfectly over P processors. Call the best speedup S.
S is at most one over s plus one minus s over P.
Scale the one-core time to 1. The serial part s stays. The parallel part, one minus s, shrinks by P. One over that new time is the speedup. As P grows, the speedup creeps up to one over s.
With s = 0.1: P = 10 gives 1 / (0.1 + 0.09), about 5.3. P = 100 gives about 9.2. No P beats 1 / 0.1 = 10.
The failure. Symptom: a change that sped up the test machine slows down production. Measure: work and span before and after, not only the time on a few cores. Fix: keep a change only if the parallelism stays well above the target P.
Chapter 5
Turn a loop into a tree of spawns and pay a logarithm for the split
Multiply an n × n matrix A by a vector x. Each output y[i] is the dot product of row i with x, and no row needs another. CLRS writes this with parallel for:
pseudocodeMAT-VEC(A, x): parallel for i = 1 to n: # rows run in parallel y[i] = 0 for j = 1 to n: # a serial inner loop y[i] = y[i] + A[i][j] * x[j] return y
A runtime cannot spawn n iterations from one strand in one step. The compiler turns parallel for into divide and conquer: split the range in half, spawn one half, recurse on the other, sync. The splits form a binary tree of depth about lg n, where lg means log base 2. Call the span of iteration i iter∞(i).
T-infinity equals theta of lg n plus the max over i of iter-infinity of i.
Walk down the splitting tree to one iteration: about lg n levels. Then run that iteration's body. The slowest body decides the rest.
MAT-VEC with n = 1,024: lg n = 10, and each body is a serial loop of 1,024 steps. Span is about 10 + 1,024, so Θ(n). Work is n × n, about 1,050,000, so parallelism is Θ(n), about 1,000.
The tree splits the range. The bar under each leaf is the body's span. Pick a body and drag n.
Illustrative units: one split level or one inner step costs 1. The "reduce" body sums the n products with a tree of depth lg n.
A reduce combines n values with an associative operation, such as +, by the same tree run upward: Θ(n) work, Θ(lg n) span. A scan (prefix sum) needs two passes over the tree, up and then down, and keeps the same costs. The scan of 3, 1, 4, 1, 5, 9, 2, 6 is 3, 4, 8, 9, 14, 23, 25, 31.
The failure. Symptom: a parallel loop over tiny bodies runs slower than the serial loop. Measure: divide the time by n; if each iteration costs more than the body, the spawns cost more than the work. Fix: give each leaf a chunk of iterations to run serially.
Chapter 6
Let two strands touch one variable and watch an update vanish
CLRS gives a three-line program:
pseudocodex = 0 parallel for i = 1 to 2: x = x + 1 print(x)
You expect 2. But the processor runs x = x + 1 as three steps: read x into a register, add 1, write the register back to x. Two strands can mix those steps.
Two strands are logically parallel when no path in the DAG orders them. A determinacy race happens when two logically parallel strands use the same memory place and at least one of them writes. The answer then depends on the schedule.
Press A or B to run that strand's next step, or press Random for a whole run. The tally counts finished runs.
Random picks one of the 20 orders of the six steps, each with the same chance.
Count the orders. Each strand keeps its own three steps in order, so there are 20 ways to mix six steps. The answer is 2 only if one strand reads after the other writes. That forces one strand to run fully first: 2 of the 20 orders. The other 18 orders print 1.
The fix in fork-join code is to share nothing until the sync. Give each strand its own place, then combine:
pseudocodea = spawn work(left) # writes only a b = work(right) # writes only b sync x = a + b # one strand, after the sync
The failure. Symptom: tests pass, and the answer is wrong once in a while in production. Measure: run a race detector, such as ThreadSanitizer, which records the strands that touch each address. Fix: write to separate places and combine after the sync, or use a reduce.
Chapter 7
Run eight block products at once and pay only for the additions on the way back
Multiply two n × n matrices: C = A · B. Each entry C[i][j] is the dot product of row i of A with column j of B. No entry needs another entry.
The loop version puts parallel for on i and on j, and keeps the k loop serial. Work is n3. Span is lg n + lg n + n, so Θ(n). Parallelism is n3/n = n2: a million for n = 1,000. If each dot product also uses a reduce, the span drops to Θ(lg n).
The recursive version comes from divide and conquer. Cut each matrix into four blocks of size n/2. C needs 8 block products, two for each quadrant. Spawn all 8: four write into C, four into a temporary matrix T. Sync. Then add T into C with a nested parallel for, which has span Θ(lg n). Call the span of this multiply on size n M∞(n).
M-infinity of n equals M-infinity of n over two plus theta of lg n, which is theta of lg squared n.
At size n, wait for one block product of size n over 2, then pay lg n for the addition. Unroll it: lg n + lg(n/2) + ... + 1. That sum is about half of lg n squared.
n = 1,024: 10 + 9 + ... + 1 = 55 units of span, against about 1,024 for the loop version. Work stays n3, so parallelism is n3/lg2 n.
Each row is one level of the recursion. Its bar is the cost of the addition at that block size. Drag n.
Illustrative units with constants dropped: the addition at block size m costs lg m. Work and parallelism use the exact count n3.
Strassen's method needs 7 block products in place of 8. In parallel it keeps the Θ(lg2 n) span with work Θ(nlg 7), about n2.81.
The failure. Symptom: the recursive multiply gives slightly different results each run. Measure: check whether two parallel products add into the same block of C. Fix: write the second product of each quadrant into T, and add after the sync. Without T, the two products must run in series, and the span grows to Θ(n).
Chapter 8
Spawn the two sorts, then make the merge split itself so it stops being the bottleneck
The easy step: spawn the sort of the left half, sort the right half, sync, then merge. The merge is serial, so the span is T∞(n/2) + Θ(n), which is Θ(n). Work stays Θ(n lg n), so parallelism is only Θ(lg n): about 20 for a million items.
P-MERGE merges two sorted arrays in parallel. Let the longer one have n1 items and the shorter n2, with n = n1 + n2.
How big can a part be? It gets at most half the longer array plus all of the shorter one: n1/2 + n2 = n − n1/2. Since n1 ≥ n/2, that is at most n − n/4 = 3n/4. Call the span of P-MERGE on n items PM∞(n).
PM-infinity of n is at most PM-infinity of three n over four plus theta of lg n, which is theta of lg squared n.
Each level pays one binary search, then waits for a part of at most three quarters of n. Shrinking by a quarter each time takes about lg n levels. lg n levels of lg n each give lg squared n.
With made-up sizes: n1 = 8, n2 = 8, and all of the shorter array below x. The lower part gets 3 + 8 = 11 of 16 items, 69%, under the 75% limit.
Top: the two sorted inputs. Bottom: the output. Each press of Split runs one level: every part picks its x, places it and splits. Green items are in their final place.
Illustrative inputs. The split rule is the CLRS rule: x is the middle item of the longer part. A binary search places it in the shorter part.
P-MERGE does Θ(n) work. Put it inside merge sort and call the span PMS∞(n).
PMS-infinity of n equals PMS-infinity of n over two plus theta of lg squared n, which is theta of lg cubed n.
Sort both halves at the same time, then run a parallel merge. Halving gives lg n levels of at most lg squared n each. Divide the work, n lg n, by that span: the parallelism is n over lg squared n.
n = 10,000,000: lg n is about 23.3, and lg squared n is about 541. Parallelism is about 10,000,000 / 541, roughly 18,500, against about 23 for the serial merge.
| Sort | Work | Span | Parallelism |
|---|---|---|---|
| Serial merge sort | Θ(n lg n) | Θ(n lg n) | 1 |
| Spawned halves, serial merge | Θ(n lg n) | Θ(n) | Θ(lg n) |
| Spawned halves, P-MERGE | Θ(n lg n) | Θ(lg3 n) | Θ(n / lg2 n) |
The failure. Symptom: the parallel merge is no faster than the serial one. Measure: log the part sizes; a part that keeps nearly all items means x came from the shorter array. Fix: take x from the longer array.
Chapter 9
Keep the terms, the numbers, the checklist and the code in one place
A parallel program is a DAG of strands. Its work says how long one core takes. Its span says how long any number of cores takes. A greedy scheduler lands within the sum of the two. So keep the work low and the span short.
| Term | Meaning | Example on this page |
|---|---|---|
| Work T1 | strands in the DAG; time on 1 core | P-FIB(4): 17; P-FIB(6): 49 |
| Span T∞ | strands on the longest path | P-FIB(4): 8; P-FIB(6): 12 |
| Work law | TP ≥ T1/P | 49 / 4 = 12.25 |
| Span law | TP ≥ T∞ | at least 12 steps |
| Greedy bound | TP ≤ T1/P + T∞ | 24.25; the run took 15 |
| Parallelism | T1/T∞ | P-FIB(30): about 89,751 |
| Slackness | parallelism / P | 2,048 / 512 = 4; 128 / 512 = 0.25 |
| Amdahl's law | speedup ≤ 1/(s + (1 − s)/P) | s = 0.1: never above 10 |
| Parallel for | span Θ(lg n) + slowest body | MAT-VEC: Θ(n) |
| Matrix multiply | recursive, with T | span Θ(lg2 n), parallelism Θ(n3/lg2 n) |
| Merge sort | with P-MERGE | span Θ(lg3 n), parallelism Θ(n/lg2 n) |
pythondef work_span(n, edges): """Strands 0..n-1 cost 1 step each; edges are (u, v): u before v.""" preds = [[] for _ in range(n)] for u, v in edges: preds[v].append(u) memo = {} def longest(v): # strands on the longest path ending at v if v not in memo: memo[v] = 1 + max((longest(u) for u in preds[v]), default=0) return memo[v] return n, max(longest(v) for v in range(n)) def greedy_steps(n, edges, P): indeg = [0] * n succ = [[] for _ in range(n)] for u, v in edges: indeg[v] += 1 succ[u].append(v) ready = [v for v in range(n) if indeg[v] == 0] steps = 0 while ready: run, ready = ready[:P], ready[P:] # up to P ready strands this step steps += 1 for u in run: for v in succ[u]: indeg[v] -= 1 if indeg[v] == 0: ready.append(v) return steps # a diamond: 0 forks to 1 and 2, both join at 3 E = [(0, 1), (0, 2), (1, 3), (2, 3)] T1, Tinf = work_span(4, E) print(T1, Tinf, greedy_steps(4, E, 2)) # 4 3 3 assert max(T1 / 2, Tinf) <= greedy_steps(4, E, 2) <= T1 / 2 + Tinf
Now press Present or Teach. Explain from memory why a greedy run never takes more than T1/P + T∞ steps, why P-FIB has span about 2n, and why P-MERGE parts stay under 3n/4. Then go back to the hero, set P-FIB(6), and find the P where more cores stop helping.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, third edition, MIT Press, Chapter 27, Multithreaded Algorithms. The strand model of P-FIB, the greedy bound, the chess numbers and the P-MERGE rule follow the book. The work-stealing bound is from R. D. Blumofe and C. E. Leiserson, "Scheduling Multithreaded Computations by Work Stealing" (1999). The devices and toy inputs on this page are our own.