TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Parallel Loops and Determinacy Races

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 nn 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:

text
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  sync

The recursion tree has nn leaves and depth ⌈lg⁡n⌉\lceil \lg n \rceil, so the loop control adds Θ(n)\Theta(n) work and Θ(lg⁡n)\Theta(\lg n) span. If iteration ii has span sis_i, the whole loop has

T∞=Θ(lg⁡n)+max⁡0≤i<nsi.T_\infty = \Theta(\lg n) + \max_{0 \le i < n} s_i .

Spawning the iterations one by one in a serial loop would instead give a span of Θ(n)\Theta(n) for the control alone, which is why every runtime splits the range recursively.

Matrix-vector product

To compute y=Axy = Ax for an n×nn \times n matrix, run the rows in parallel; each row is a dot product. Two choices for the inner loop:

text
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 Θ(n2)\Theta(n^2) and the span Θ(lg⁡n)+Θ(n)=Θ(n)\Theta(\lg n) + \Theta(n) = \Theta(n), so the parallelism is Θ(n)\Theta(n). Computing each dot product with a parallel reduction (a P-SUM over the nn products) lowers the span to Θ(lg⁡n)\Theta(\lg n) and raises the parallelism to Θ(n2/lg⁡n)\Theta(n^2/\lg n), at the price of some extra work. The program computes both exactly with the composition rules, with unit strands.

python · try it yourself
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 n=4096n = 4096 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:

text
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 count

The serial projection returns nn. 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.

python · try it yourself
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 ii adds its left neighbour.

text
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 ii reads the new value of A[i - 1]. But iterations i−1i - 1 and ii are logically in parallel, and iteration i−1i - 1 writes the location that iteration ii 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.

python · try it yourself
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 Θ(n)\Theta(n) work with Θ(lg⁡n)\Theta(\lg n) 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 different y[i]; only reads are shared. Making the inner loop a parallel y[i] = y[i] + ... would race on y[i], which is why the parallel version uses a reduction.
  • Reductions instead of shared accumulators. OpenMP's reduction(+:sum), oneTBB's parallel_reduce and C++17's std::reduce with 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 kk racing increments lose at least one update.

cpp · try it yourself
#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, k!k! of the (2k)!/2k(2k)!/2^k.

Test yourself

What is the span of a parallel for with nn iterations whose bodies each have span Θ(1)\Theta(1)?

  1. Θ(1)\Theta(1)
  2. Θ(lg⁡n)\Theta(\lg n)
  3. Θ(n)\Theta(n)
  4. Θ(nlg⁡n)\Theta(n \lg n)

Which situation is a determinacy race?

  1. Two strands in series write the same location
  2. Two logically parallel strands read the same location
  3. Two logically parallel strands access the same location and at least one writes it
  4. 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. 1
  2. 2
  3. 4
  4. 6

Why is a parallel loop not spawned as for i: spawn body(i) in a serial loop?

  1. It would race
  2. Its span would be Θ(n)\Theta(n) for the loop control alone
  3. It would do more work
  4. It is not allowed by the model