TExcelTAD

Parallel Builds

A machine with 16 cores that compiles one file at a time is 94% idle. Because every translation unit compiles independently, C and C++ builds parallelise very well: make -j16, ninja (parallel by default), cmake --build build -j 16. The build graph says what may run together: any step whose inputs are all finished.

A scheduler with N workers

The model below is the core loop of every parallel build executor. Each step has a duration (made-up seconds); workers take ready steps in a fixed priority order; when a step finishes, the steps that waited for it may become ready. The simulation is event-driven and deterministic, so the printed schedule is the same on every run:

js · try it yourself
const steps = {   // name: [seconds, inputs]
  "parse.o": [4, []], "lexer.o": [3, []], "eval.o": [5, []], "gc.o": [2, []],
  "libcore.a": [1, ["parse.o", "lexer.o", "eval.o", "gc.o"]],
  "main.o": [2, []], "repl.o": [3, []],
  "app": [2, ["libcore.a", "main.o", "repl.o"]],
  "tests": [4, ["app"]],
};

function schedule(workers, verbose) {
  const done = new Set(), running = [];     // running: {name, end, worker}
  const free = [...Array(workers).keys()];
  let now = 0;
  const lines = [];
  while (done.size < Object.keys(steps).length) {
    const busy = new Set([...done, ...running.map((r) => r.name)]);
    const ready = Object.keys(steps).filter((s) => !busy.has(s) && steps[s][1].every((i) => done.has(i)));
    while (free.length && ready.length) {             // start as much as we can
      const name = ready.shift(), worker = free.shift();
      running.push({ name, end: now + steps[name][0], worker });
      lines.push(`t=${String(now).padStart(2)}  worker ${worker} starts ${name}`);
    }
    running.sort((a, b) => a.end - b.end || a.worker - b.worker);
    const finished = running.shift();                 // jump to the next finish
    now = finished.end;
    done.add(finished.name);
    free.push(finished.worker);
    free.sort();
  }
  if (verbose) console.log(lines.join("\n"));
  return now;
}

schedule(2, true);
for (const n of [1, 2, 3, 4, 8]) console.log(`${n} worker(s): finished at t=${schedule(n)}`);
t= 0  worker 0 starts parse.o
t= 0  worker 1 starts lexer.o
t= 3  worker 1 starts eval.o
t= 4  worker 0 starts gc.o
t= 6  worker 0 starts main.o
t= 8  worker 0 starts repl.o
t= 8  worker 1 starts libcore.a
t=11  worker 0 starts app
t=13  worker 0 starts tests
1 worker(s): finished at t=26
2 worker(s): finished at t=17
3 worker(s): finished at t=14
4 worker(s): finished at t=12
8 worker(s): finished at t=12

Two lessons hide in those numbers:

  • Speed-up flattens. One worker needs the sum of all durations (26 s). More workers help until the build is limited by its critical path, the longest chain of dependent steps: eval.o → libcore.a → app → tests = 5 + 1 + 2 + 4 = 12 s. No number of cores beats 12 s; only shortening that chain does.
  • Link and test steps serialise. libcore.a, app and tests each wait for everything before them. Large projects split one giant library or test binary into several so that more of the graph can overlap.

Choosing -j

Setting Effect
make (no -j) one job at a time; GNU Make's default
make -j N at most N jobs; -j$(nproc) matches the core count
make -j (no number) unlimited jobs: can start hundreds of compilers and run out of memory
ninja defaults to cores + 2; ninja -j1 for one job
make -l 8 don't start new jobs while the load average is above 8

C++ compiles can use 1–2 GB of memory each, so on big projects memory, not cores, often sets the limit. Linking is the most memory-hungry step; Ninja's pool feature (and CMake's JOB_POOL_LINK) caps how many links run at once.

Parallel builds also interleave output: lines from different compilers mix in the terminal. make -O (--output-sync) buffers each job's output and prints it in one piece; Ninja always does this. The sessions in this course use -j1 for exactly this reason: the output must be identical on every run.

The bug that only appears with -j

A serial build runs steps in the order Make reads them, which can hide a missing edge in the graph. Here app needs the generated version.h but doesn't say so; the all target just happens to list version.h first:

bash · try it yourself
mkdir -p par && cd par
printf '#include <stdio.h>\n#include "version.h"\nint main(void) { puts("version " VERSION); return 0; }\n' > main.c
cat > Makefile <<'MK'
all: version.h app
version.h:
	sleep 1; echo '#define VERSION "1.4.2"' > version.h
app: main.c
	gcc main.c -o app
MK
echo "--- make -j1"
make -j1 && ./app
rm -f version.h app
echo "--- make -j2"
make -j2
echo "exit status: $?"
--- make -j1
sleep 1; echo '#define VERSION "1.4.2"' > version.h
gcc main.c -o app
version 1.4.2
--- make -j2
sleep 1; echo '#define VERSION "1.4.2"' > version.h
gcc main.c -o app
main.c:2:10: fatal error: version.h: No such file or directory
    2 | #include "version.h"
      |          ^~~~~~~~~~~
compilation terminated.
make: *** [Makefile:5: app] Error 1
make: *** Waiting for unfinished jobs....
exit status: 2

With two jobs, Make starts the generator and the compile at the same time, and the compiler looks for version.h before it exists. (The sleep 1 makes the race lose every time; in real projects it loses only sometimes, which is worse.) The fix is the missing edge, app: main.c version.h, after which -j2 waits correctly. Treat "works with -j1, fails with -jN" as a bug in the build graph, never as a reason to build serially.

Test yourself

In the model, why can't 8 workers finish faster than t=12?

  1. The model limits workers
  2. 12 s is the critical path, the longest chain of steps that must run one after another
  3. The machine is too slow
  4. Linking can't run in parallel

A build works with make -j1 but fails at random with make -j8. What is the likely cause?

  1. A compiler bug
  2. A missing dependency edge: some step uses a file the graph doesn't say it needs
  3. Too little disk space
  4. -j8 is not supported

What does make -O do?

  1. Optimises the code
  2. Groups each job's output together instead of interleaving lines
  3. Runs one job only
  4. Builds out of tree