TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › The Fork-Join Model and Computation DAGs

The Fork-Join Model and Computation DAGs

A laptop today has eight or more cores, yet every algorithm in this track so far ran on one of them. Writing programs that use all the cores directly, with threads, locks and messages, is notoriously hard: the programmer has to decide which core does what, balance the load and avoid stepping on shared data. Fork-join parallelism (also called dynamic multithreading or task parallelism) moves most of that burden to a runtime system. The programmer only says what may run in parallel; a scheduler decides where and when. This lesson introduces the model and the object every later lesson analyses: the computation DAG of a run.

Three keywords

A fork-join program is an ordinary serial program plus three keywords:

  • spawn in front of a procedure call: the caller may keep running while the callee runs, possibly in parallel. The spawn says the two may run at the same time, not that they must.
  • sync: wait until every child spawned by this procedure call so far has returned. Every procedure also syncs implicitly before it returns.
  • parallel for: the iterations of the loop may run in parallel (the lesson Parallel Loops and Determinacy Races shows how it is built from spawns).

Here is a parallel sum of an array, written in the track's pseudocode:

text
P-SUM(A, lo, hi)               // the sum of A[lo .. hi - 1], hi - lo >= 1
1  if hi - lo == 1
2      return A[lo]
3  mid = floor((lo + hi) / 2)
4  x = spawn P-SUM(A, lo, mid)  // the left half may run in parallel ...
5  y = P-SUM(A, mid, hi)        // ... with the right half
6  sync                         // wait for x
7  return x + y

Delete the keywords spawn and sync and what remains is an ordinary recursive sum. That program is the serial projection of the parallel one. A well-written fork-join program computes exactly what its serial projection computes; the keywords only permit parallelism. This is a big advantage over raw threads: you can test and debug the serial projection, and reasoning about correctness stays sequential. The one way to break it, a determinacy race, is the subject of a later lesson.

The model assumes a shared memory: all processors see the same array A. It is an idealized machine, like the RAM model of The RAM Model, with any number of processors of equal speed and no cost for spawning or for memory contention. Real costs appear later as constant factors.

The computation DAG

To analyse a run, record it as a graph. A strand is a maximal sequence of instructions that contains no spawn, sync or return; it is executed by one processor without interruption. The computation DAG has one vertex per strand and an edge u→vu \to v when vv cannot start before uu ends:

Edge Meaning
spawn edge from the strand that spawns to the first strand of the child
call edge from the strand that makes an ordinary call to the first strand of the callee (here combined with the continuation of the parent)
return edge from the last strand of a child to the strand after the parent's sync (or after the call)

Two strands are logically in series if there is a path from one to the other, and logically in parallel otherwise. The DAG depends only on the program and its input, never on how many processors there are or how the scheduler behaves, which is what makes it a good object of analysis.

The program below runs P-SUM on four numbers while recording the DAG. Each internal call contributes a split strand (lines 1 to 4) and an add strand (line 7); each base case is one leaf strand.

python · try it yourself
class Dag:
    def __init__(self):
        self.labels, self.edges = [], []

    def strand(self, label):
        self.labels.append(label)
        return len(self.labels) - 1

    def edge(self, u, v, kind):
        self.edges.append((u, v, kind))

def p_sum(dag, A, lo, hi):
    """returns (sum of A[lo:hi], first strand, last strand) and records the DAG"""
    if hi - lo == 1:
        s = dag.strand(f"leaf {lo}")
        return A[lo], s, s
    mid = (lo + hi) // 2
    u = dag.strand(f"split [{lo},{hi})")
    x, f1, l1 = p_sum(dag, A, lo, mid)     # spawned
    dag.edge(u, f1, "spawn")
    y, f2, l2 = p_sum(dag, A, mid, hi)     # called
    dag.edge(u, f2, "call")
    v = dag.strand(f"add [{lo},{hi})")     # after the sync
    dag.edge(l1, v, "return")
    dag.edge(l2, v, "return")
    return x + y, u, v

dag = Dag()
total, first, last = p_sum(dag, [5, 1, 4, 2], 0, 4)
print("sum =", total)
for i, label in enumerate(dag.labels):
    print(f"  strand {i}: {label}")
for u, v, kind in sorted(dag.edges):
    print(f"  {u} -> {v}  ({kind})")
sum = 12
  strand 0: split [0,4)
  strand 1: split [0,2)
  strand 2: leaf 0
  strand 3: leaf 1
  strand 4: add [0,2)
  strand 5: split [2,4)
  strand 6: leaf 2
  strand 7: leaf 3
  strand 8: add [2,4)
  strand 9: add [0,4)
  0 -> 1  (spawn)
  0 -> 5  (call)
  1 -> 2  (spawn)
  1 -> 3  (call)
  2 -> 4  (return)
  3 -> 4  (return)
  4 -> 9  (return)
  5 -> 6  (spawn)
  5 -> 7  (call)
  6 -> 8  (return)
  7 -> 8  (return)
  8 -> 9  (return)

Ten strands and twelve edges for four numbers. In general, nn numbers give nn leaves, n−1n - 1 split strands and n−1n - 1 add strands, so 3n−23n - 2 strands and 4(n−1)4(n - 1) edges: two leave each split strand and two enter each add strand.

Series or parallel?

Which strands may run at the same time? The next program computes, for every pair of strands, whether one can reach the other, and lists the pairs that are logically in parallel. Each pair consists of one strand from the left subtree and one from the right subtree of some split strand.

python · try it yourself
def p_sum_dag(n):
    labels, edges = [], []
    def rec(lo, hi):
        if hi - lo == 1:
            labels.append(f"leaf {lo}")
            return len(labels) - 1, len(labels) - 1
        mid = (lo + hi) // 2
        labels.append(f"split [{lo},{hi})"); u = len(labels) - 1
        f1, l1 = rec(lo, mid)
        f2, l2 = rec(mid, hi)
        labels.append(f"add [{lo},{hi})"); v = len(labels) - 1
        edges.extend([(u, f1), (u, f2), (l1, v), (l2, v)])
        return u, v
    rec(0, n)
    return labels, edges

labels, edges = p_sum_dag(4)
succ = {i: [] for i in range(len(labels))}
for u, v in edges:
    succ[u].append(v)

def reachable(s):
    seen, stack = {s}, [s]
    while stack:
        for w in succ[stack.pop()]:
            if w not in seen:
                seen.add(w); stack.append(w)
    return seen

reach = [reachable(i) for i in range(len(labels))]
parallel = [(a, b) for a in range(len(labels)) for b in range(a + 1, len(labels))
            if b not in reach[a] and a not in reach[b]]
print(len(parallel), "pairs of strands are logically in parallel:")
for a, b in parallel:
    print(f"  {labels[a]:12} || {labels[b]}")
18 pairs of strands are logically in parallel:
  split [0,2)  || split [2,4)
  split [0,2)  || leaf 2
  split [0,2)  || leaf 3
  split [0,2)  || add [2,4)
  leaf 0       || leaf 1
  leaf 0       || split [2,4)
  leaf 0       || leaf 2
  leaf 0       || leaf 3
  leaf 0       || add [2,4)
  leaf 1       || split [2,4)
  leaf 1       || leaf 2
  leaf 1       || leaf 3
  leaf 1       || add [2,4)
  add [0,2)    || split [2,4)
  add [0,2)    || leaf 2
  add [0,2)    || leaf 3
  add [0,2)    || add [2,4)
  leaf 2       || leaf 3

The leaf for A[0] may run in parallel with anything belonging to the right half, but never with its own parent's split strand (which must come first) or with the add strand that consumes it. A scheduler with enough processors could run all four leaves at once.

Many legal executions, one answer

An execution on any number of processors corresponds to a way of running the strands that respects the edges: on one processor, a topological order of the DAG (Topological Sort). Different schedulers pick different orders. Since every strand of P-SUM writes only its own local result, every order gives the same sum. The program executes the DAG for eight numbers twice, once always picking the ready strand with the smallest number and once the largest, and records the order in which the leaves run.

python · try it yourself
import heapq

def p_sum_dag(A):
    labels, edges, op = [], [], []
    def rec(lo, hi):
        if hi - lo == 1:
            labels.append(f"leaf {lo}"); op.append(("leaf", lo, None))
            return len(labels) - 1, len(labels) - 1
        mid = (lo + hi) // 2
        labels.append("split"); op.append(("split", None, None)); u = len(labels) - 1
        f1, l1 = rec(lo, mid)
        f2, l2 = rec(mid, hi)
        labels.append("add"); op.append(("add", l1, l2)); v = len(labels) - 1
        edges.extend([(u, f1), (u, f2), (l1, v), (l2, v)])
        return u, v
    rec(0, len(A))
    return labels, edges, op

def execute(A, pick_largest):
    labels, edges, op = p_sum_dag(A)
    indeg = [0] * len(labels)
    succ = [[] for _ in labels]
    for u, v in edges:
        succ[u].append(v); indeg[v] += 1
    ready = [(-i if pick_largest else i) for i in range(len(labels)) if indeg[i] == 0]
    value, leaves = {}, []
    while ready:
        s = abs(heapq.heappop(ready))
        kind, a, b = op[s]
        if kind == "leaf":
            value[s] = A[a]; leaves.append(a)
        elif kind == "add":
            value[s] = value[a] + value[b]
        for w in succ[s]:
            indeg[w] -= 1
            if indeg[w] == 0:
                heapq.heappush(ready, -w if pick_largest else w)
    return value[s], leaves

A = [5, 1, 4, 2, 8, 3, 7, 6]
for name, flag in [("smallest ready first", False), ("largest ready first", True)]:
    total, leaves = execute(A, flag)
    print(f"{name:21}: leaves run in order {leaves}, sum = {total}")
smallest ready first : leaves run in order [0, 1, 2, 3, 4, 5, 6, 7], sum = 36
largest ready first  : leaves run in order [7, 6, 5, 4, 3, 2, 1, 0], sum = 36

The two orders are mirror images, and the answer is 36 both times. The DAG is the program's meaning; the order is the scheduler's business.

In C++

The C++ version builds the same DAG for eight numbers, checks the strand and edge counts and finds the length of the longest path (in strands), a number the next lesson names the span. Compiler Explorer cannot start threads, so the program records the DAG instead of running it in parallel.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <utility>
#include <vector>

std::vector<std::pair<int, int>> edges;
int strands = 0;

std::pair<int, int> p_sum_dag(int lo, int hi) {          // returns (first, last) strand
    if (hi - lo == 1) { int s = strands++; return {s, s}; }
    int mid = (lo + hi) / 2;
    int u = strands++;                                    // split strand
    auto [f1, l1] = p_sum_dag(lo, mid);                   // spawned child
    auto [f2, l2] = p_sum_dag(mid, hi);                   // called child
    int v = strands++;                                    // add strand after the sync
    edges.insert(edges.end(), {{u, f1}, {u, f2}, {l1, v}, {l2, v}});
    return {u, v};
}

int main() {
    for (int n : {4, 8, 16}) {
        edges.clear(); strands = 0;
        p_sum_dag(0, n);
        // strands are numbered so that every edge goes from a smaller to a larger number
        std::vector<int> longest(strands, 1);
        std::sort(edges.begin(), edges.end());
        for (auto [u, v] : edges) longest[v] = std::max(longest[v], longest[u] + 1);
        std::printf("n = %2d: %2d strands, %2d edges, longest path %d strands\n",
                    n, strands, (int)edges.size(), *std::max_element(longest.begin(), longest.end()));
    }
}
n =  4: 10 strands, 12 edges, longest path 5 strands
n =  8: 22 strands, 28 edges, longest path 7 strands
n = 16: 46 strands, 60 edges, longest path 9 strands

The longest path grows like 2lg⁡n+12\lg n + 1 while the number of strands grows like 3n3n: that gap between total work and the longest chain of dependences is the whole story of parallel speedup.

On a real machine the same algorithm would use std::async (or a task library such as oneTBB, or OpenMP tasks), whose structure mirrors the pseudocode line by line. This block is for reading, not for running here:

cpp
#include <future>
#include <vector>

long long p_sum(const std::vector<long long>& a, size_t lo, size_t hi) {
    if (hi - lo < 4096) {                          // coarsen: small ranges run serially
        long long s = 0;
        for (size_t i = lo; i < hi; i++) s += a[i];
        return s;
    }
    size_t mid = lo + (hi - lo) / 2;
    auto x = std::async(std::launch::async, p_sum, std::cref(a), lo, mid);   // spawn
    long long y = p_sum(a, mid, hi);
    return x.get() + y;                            // sync
}

Real runtimes do not create a thread per spawn; a work-stealing scheduler keeps one worker per core and lets idle workers steal spawned tasks from busy ones. The base case is also coarsened, because a spawn costs far more than adding two numbers. The model ignores both points, and the next lessons show why that is a reasonable first approximation.

Test yourself

What is the serial projection of a fork-join program?

  1. The program run on one processor with a scheduler
  2. The program with the keywords spawn and sync deleted (and parallel for turned into for)
  3. The longest path in its computation DAG
  4. The program with every call spawned

Two strands of a computation DAG are logically in parallel when

  1. they are executed by different processors
  2. there is no path from either one to the other
  3. they were spawned by the same procedure
  4. they have the same number of instructions

How many strands does the DAG of P-SUM have for n=16n = 16 numbers, in the model of this lesson?

  1. 16
  2. 31
  3. 46
  4. 64

Why does the computation DAG not depend on the number of processors?

  1. Because the scheduler is deterministic
  2. Because it records only which strands must precede which, a property of the program and its input
  3. Because all strands take the same time
  4. Because shared memory has no cost