Parallel Loops and Determinacy Races
Most parallel speedup in practice comes from loops whose iterations are independent: scale every pixel, update every particle, compute every row of a product. The parallel for keyword expresses that directly. This lesson shows how a parallel loop is built from spawns, what it costs in span, and the one bug that breaks the fork-join model's promise that a parallel program means the same as its serial projection: the determinacy race.
Building a parallel loop
A parallel for over iterations is compiled into a divide-and-conquer recursion over the index range, exactly like P-SUM of The Fork-Join Model and Computation DAGs:
PARALLEL-LOOP(lo, hi, body) // run body(i) for lo <= i < hi, in parallel
1 if hi - lo == 1
2 body(lo)
3 return
4 mid = floor((lo + hi) / 2)
5 spawn PARALLEL-LOOP(lo, mid, body)
6 PARALLEL-LOOP(mid, hi, body)
7 syncThe recursion tree has leaves and depth , so the loop control adds work and span. If iteration has span , the whole loop has
Spawning the iterations one by one in a serial loop would instead give a span of for the control alone, which is why every runtime splits the range recursively.
Matrix-vector product
To compute for an matrix, run the rows in parallel; each row is a dot product. Two choices for the inner loop:
MAT-VEC(A, x, y, n)
1 parallel for i = 0 to n - 1
2 y[i] = 0
3 for j = 0 to n - 1 // serial inner loop
4 y[i] = y[i] + A[i][j] * x[j]With the serial inner loop, the work is and the span , so the parallelism is . Computing each dot product with a parallel reduction (a P-SUM over the products) lowers the span to and raises the parallelism to , at the price of some extra work. The program computes both exactly with the composition rules, with unit strands.
from functools import lru_cache
@lru_cache(maxsize=None)
def loop_ws(n, w_iter, s_iter):
"""parallel loop of n iterations, each with work w_iter and span s_iter"""
if n == 1:
return w_iter, s_iter
w1, s1 = loop_ws(n // 2, w_iter, s_iter)
w2, s2 = loop_ws(n - n // 2, w_iter, s_iter)
return w1 + w2 + 1, max(s1, s2) + 1 # one split strand per level
@lru_cache(maxsize=None)
def reduce_ws(n):
"""P-SUM over n products: leaves cost 1 (multiply), split and add strands cost 1"""
if n == 1:
return 1, 1
w1, s1 = reduce_ws(n // 2)
w2, s2 = reduce_ws(n - n // 2)
return w1 + w2 + 2, max(s1, s2) + 2
print(" n serial inner: work span par. parallel inner: work span par.")
for n in [8, 64, 512, 4096]:
wa, sa = loop_ws(n, n + 1, n + 1) # y[i] = 0, then n updates
wi, si = reduce_ws(n)
wb, sb = loop_ws(n, wi + 1, si + 1) # the reduction, then one store
print(f"{n:6} {wa:19} {sa:6} {wa / sa:6.0f} {wb:21} {sb:6} {wb / sb:8.0f}") n serial inner: work span par. parallel inner: work span par.
8 79 12 7 191 11 17
64 4223 71 59 12287 20 614
512 263167 522 504 786431 29 27118
4096 16785407 4109 4085 50331647 38 1324517
For the serial inner loop leaves a parallelism of about 4000, already plenty for any multicore; the parallel reduction pushes it past a million but triples the work. On a real machine the first version is the better one: the extra work is real, the extra parallelism is unusable.
Determinacy races
A determinacy race occurs when two logically parallel strands access the same memory location and at least one of them writes it. The outcome then depends on the order in which the scheduler happens to run them, and the program may give different answers on different runs.
The classic case is a shared counter. Each count = count + 1 is really two machine steps, a load into a register and a store back:
RACY-COUNT(n)
1 count = 0
2 parallel for i = 0 to n - 1
3 r = count // load
4 count = r + 1 // store
5 return countThe serial projection returns . In parallel, if two strands both load before either stores, one increment is lost. The program enumerates every interleaving of the strands' steps (each strand keeps its own order) and counts the final values.
from collections import Counter
def interleavings(k):
"""final values of count over all interleavings of k strands doing load, store"""
results = Counter()
def run(pc, reg, count):
if all(p == 2 for p in pc):
results[count] += 1
return
for s in range(k):
if pc[s] == 0: # load
run(pc[:s] + (1,) + pc[s + 1:], reg[:s] + (count,) + reg[s + 1:], count)
elif pc[s] == 1: # store
run(pc[:s] + (2,) + pc[s + 1:], reg, reg[s] + 1)
run((0,) * k, (0,) * k, 0)
return results
for k in [2, 3, 4]:
res = interleavings(k)
total = sum(res.values())
print(f"{k} strands: {total:4} interleavings, final count:",
", ".join(f"{v} in {c}" for v, c in sorted(res.items())))2 strands: 6 interleavings, final count: 1 in 4, 2 in 2
3 strands: 90 interleavings, final count: 1 in 48, 2 in 36, 3 in 6
4 strands: 2520 interleavings, final count: 1 in 1152, 2 in 1056, 3 in 288, 4 in 24
With two strands, 4 of the 6 interleavings lose an update. With four strands only 24 of 2520 interleavings give the right answer 4, and every value from 1 to 4 is possible. Testing cannot be relied on to find such bugs: on a lightly loaded machine the "right" interleavings may happen to occur almost every time, and the wrong answer appears once a month in production.
A race in disguise
Races are not always this visible. Here is an attempt at prefix sums: iteration adds its left neighbour.
parallel for i = 1 to n - 1
A[i] = A[i] + A[i - 1]Run serially, from left to right, it computes prefix sums, because iteration reads the new value of A[i - 1]. But iterations and are logically in parallel, and iteration writes the location that iteration reads. A simple detector lists every pair of iterations of a parallel loop (all pairwise parallel) whose access sets conflict; then the program runs the loop in two legal orders.
def accesses(i):
return {"reads": {i, i - 1}, "writes": {i}}
n = 6
races = []
for a in range(1, n):
for b in range(a + 1, n):
A, B = accesses(a), accesses(b)
if A["writes"] & (B["reads"] | B["writes"]) or B["writes"] & A["reads"]:
races.append((a, b))
print("racing iteration pairs:", races)
def run(order):
A = [3, 1, 4, 1, 5, 9]
for i in order:
A[i] = A[i] + A[i - 1]
return A
print("left to right (serial projection):", run(range(1, n)))
print("right to left (also legal): ", run(range(n - 1, 0, -1)))racing iteration pairs: [(1, 2), (2, 3), (3, 4), (4, 5)]
left to right (serial projection): [3, 4, 8, 9, 14, 23]
right to left (also legal): [3, 4, 5, 5, 6, 14]
Two schedules, two answers. The fix is not to add locks, which would serialize the loop, but to use an algorithm without the dependence: parallel prefix sums use a reduction tree like P-SUM and achieve work with span. Similarly the racy counter becomes a race-free reduction: give each strand its own partial count and add the partial counts in a tree.
Avoiding races
- Write disjoint locations. In
MAT-VEC, the iterations of the parallel loop write differenty[i]; only reads are shared. Making the inner loop a parallely[i] = y[i] + ...would race ony[i], which is why the parallel version uses a reduction. - Reductions instead of shared accumulators. OpenMP's
reduction(+:sum), oneTBB'sparallel_reduceand C++17'sstd::reducewith an execution policy all do this. - Tools. Race detectors such as ThreadSanitizer (for threads) and the Cilksan detector (for fork-join programs) find races in a test run; for fork-join programs a detector can check one serial execution and report every race that any schedule could expose, because races depend only on the DAG.
Atomic instructions and locks make an individual access safe, but they serialize contended updates and are a different subject, concurrency control; the Threads and Synchronization lessons of the Operating Systems course introduce them.
In C++
The interleaving enumerator in C++, counting how many interleavings of racing increments lose at least one update.
#include <array>
#include <cstdio>
#include <map>
int k;
std::map<int, long long> results;
void run(std::array<int, 6> pc, std::array<int, 6> reg, int count) {
bool done = true;
for (int s = 0; s < k; s++) {
if (pc[s] == 2) continue;
done = false;
auto p = pc, r = reg;
if (pc[s] == 0) { p[s] = 1; r[s] = count; run(p, r, count); } // load
else { p[s] = 2; run(p, r, reg[s] + 1); } // store
}
if (done) results[count]++;
}
int main() {
for (k = 2; k <= 5; k++) {
results.clear();
run({}, {}, 0);
long long total = 0;
for (auto [v, c] : results) total += c;
std::printf("%d strands: %6lld interleavings, %6lld correct (%.2f%%)\n",
k, total, results[k], 100.0 * results[k] / total);
}
}2 strands: 6 interleavings, 2 correct (33.33%)
3 strands: 90 interleavings, 6 correct (6.67%)
4 strands: 2520 interleavings, 24 correct (0.95%)
5 strands: 113400 interleavings, 120 correct (0.11%)
The fraction of interleavings that keep every update falls quickly, from one third with two strands to about a tenth of a percent with five. The correct outcomes are exactly the interleavings in which the strands run one after another, of the .
Test yourself
What is the span of a parallel for with iterations whose bodies each have span ?
Which situation is a determinacy race?
- Two strands in series write the same location
- Two logically parallel strands read the same location
- Two logically parallel strands access the same location and at least one writes it
- One strand writes a location twice
Two strands each execute r = count; count = r + 1 on a shared count that starts at 0. In how many of the 6 interleavings is the final value 2?
- 1
- 2
- 4
- 6
Why is a parallel loop not spawned as for i: spawn body(i) in a serial loop?
- It would race
- Its span would be for the loop control alone
- It would do more work
- It is not allowed by the model