TExcelTAD
Home › GNU Make & Ninja › Parallel Builds with -j

Parallel Builds with -j

Make runs one recipe at a time unless you ask for more. make -j8 lets it run up to eight recipes at once, which on a modern machine often cuts a C build's time by five times or more. Everything in this course uses -j1 so that the printed output is identical on every run; this lesson explains what changes when you raise it, using a model you can run and edit.

What -j does

Option Meaning
-j N run up to N recipes at the same time
-j (no number) no limit at all; dangerous on big projects (hundreds of compilers at once)
-l N don't start new jobs while the load average is above N
-O / --output-sync=target buffer each target's output and print it in one piece when it finishes (GNU Make 4.0+)
-k keep going after a failure, building whatever doesn't depend on it

Make starts any target whose prerequisites are all up to date, as long as fewer than N jobs are running. The dependency graph is the only thing that orders work. The order in which prerequisites are written does not order anything under -j.

A model: N workers on a build graph

This model schedules compile and link jobs (durations in seconds) on N workers, the way make -jN does: whenever a worker is free, start the next job whose inputs are done.

js · try it yourself
const jobs = {
  'parse.o':  { secs: 4, deps: [] },
  'lexer.o':  { secs: 3, deps: [] },
  'eval.o':   { secs: 5, deps: [] },
  'main.o':   { secs: 1, deps: [] },
  'libcalc.a': { secs: 1, deps: ['parse.o', 'lexer.o', 'eval.o'] },
  'calc':     { secs: 2, deps: ['main.o', 'libcalc.a'] },
};

function simulate(n) {
  const done = new Map();          // name -> finish time
  const running = [];              // { name, end }
  const order = Object.keys(jobs); // Make's order: as written
  let t = 0;
  const log = [];
  while (done.size < order.length) {
    for (const name of order) {
      const ready = !done.has(name) && !running.some((r) => r.name === name) &&
        jobs[name].deps.every((d) => done.has(d));
      if (ready && running.length < n) {
        running.push({ name, end: t + jobs[name].secs });
        log.push(`t=${t}s start ${name}`);
      }
    }
    running.sort((a, b) => a.end - b.end || a.name.localeCompare(b.name));
    const next = running.shift();
    t = next.end;
    done.set(next.name, t);
  }
  return { t, log };
}

for (const n of [1, 2, 4]) {
  const { t, log } = simulate(n);
  console.log(`-j${n}: finished at ${t}s`);
  if (n === 2) log.forEach((line) => console.log('   ' + line));
}
-j1: finished at 16s
-j2: finished at 11s
   t=0s start parse.o
   t=0s start lexer.o
   t=3s start eval.o
   t=4s start main.o
   t=8s start libcalc.a
   t=9s start calc
-j4: finished at 8s

Two things show up. First, -j4 finishes at 8 seconds because eval.o → libcalc.a → calc takes 8 seconds whatever N is. That chain is the critical path, and it's the lower bound for any parallel build. Splitting a giant source file, or breaking a dependency that serialises the graph, helps more than adding cores once you reach it.

Second, the -j2 trace shows a scheduling choice that costs time: the longest job, eval.o, starts only at t=3 because it's written third. Make picks ready jobs in the order they appear, without knowing how long they take. Move eval.o to the top of jobs and run the model again: -j2 drops from 11 to 10 seconds, the best two workers can do here. (Ninja has the same blind spot in principle; its scheduler model looks at that.)

The bug that -j1 hides

Under -j1, Make builds prerequisites left to right, so a Makefile can happen to work because something is listed before what needs it. Here main.c includes a generated version.h, but the Makefile never says so. With version.h listed first it builds; swap the order (which is what parallel scheduling effectively does at random) and it fails:

bash · try it yourself
mkdir -p race && cd race
printf '#include <stdio.h>\n#include "version.h"\nint main(void) { puts(VERSION); return 0; }\n' > main.c
for order in "version.h main.o" "main.o version.h"; do
  printf 'app: %s\n\tgcc main.o -o $@\nversion.h:\n\techo %s > $@\nmain.o: main.c\n\tgcc -c 
lt; -o $@\n' \ "$order" "'#define VERSION \"1.2\"'" > Makefile rm -f app main.o version.h echo "=== app: $order" make -j1 2>&1 | grep -v '^compilation terminated' done
=== app: version.h main.o
echo '#define VERSION "1.2"' > version.h
gcc -c main.c -o main.o
gcc main.o -o app
=== app: main.o version.h
gcc -c main.c -o main.o
main.c:2:10: fatal error: version.h: No such file or directory
    2 | #include "version.h"
      |          ^~~~~~~~~~~
make: *** [Makefile:6: main.o] Error 1

With -j2, the first order fails too, some of the time: both version.h and main.o are ready at the start and may run together. The fix is to state the real dependency (main.o: main.c version.h), after which every order and every -j works. A useful habit is to build once with a high -j in CI; it shakes out these missing edges early. (GNU Make 4.4 added --shuffle, which randomises prerequisite order on purpose to find them; the 4.3 used here doesn't have it.)

The jobserver: one budget for all sub-makes

With recursive make, each sub-make would happily start N jobs of its own. GNU Make avoids that with a jobserver: the top-level Make holds N tokens, and every sub-make started through $(MAKE) must take a token before running an extra job. The token channel is passed down in MAKEFLAGS:

bash · try it yourself
mkdir -p js/sub && cd js
printf 'show:\n\t@echo "sub-make sees MAKEFLAGS=[$(MAKEFLAGS)]"\n' > sub/Makefile
printf 'all:\n\t+@$(MAKE) --no-print-directory -C sub\n' > Makefile
make -j1
make -j4
sub-make sees MAKEFLAGS=[ -j1 --no-print-directory]
sub-make sees MAKEFLAGS=[ -j4 --jobserver-auth=3,4 --no-print-directory]

Even with -j1, MAKEFLAGS carries the options (here -j1 and --no-print-directory) to the sub-make; with -j4 it also carries the jobserver's file descriptors. The + prefix marks the line as a recursive call even if Make couldn't spot $(MAKE) in it. Ninja 1.13 also understands this protocol as a client: run inside a make -j recipe, it takes its job slots from Make's budget instead of starting its own CPU-count worth of jobs.

Output under -j

When several recipes run at once, their output interleaves line by line, and compiler errors from two files can get mixed up. -O (--output-sync=target) collects each target's output and prints it as a block when that target finishes. The blocks then come out in completion order, which still varies between runs; that's why the sessions in this course stay at -j1.

Test yourself

A Makefile builds correctly with -j1 but sometimes fails with -j8. What is the most likely cause?

  1. A compiler bug
  2. A missing dependency edge that the left-to-right order happened to hide
  3. Too little memory
  4. Make's jobserver is broken

In the model, why does -j4 barely beat -j2?

  1. Make can't use four cores
  2. The critical path eval.o → libcalc.a → calc limits the total time
  3. Linking is always serial
  4. The model is wrong

How do sub-makes started with $(MAKE) share the -j limit?

  1. Each gets its own N jobs
  2. Through the jobserver, whose token channel is passed in MAKEFLAGS
  3. They don't run in parallel at all
  4. Through a lock file