Part 0 · 2 chapters · ~12 min
Processes and Threads
What a process is (address space, threads, kernel state), process states, fork, exec and wait, threads and their shared memory, context switches and their cost, measured costs on this machine, zombies and orphans, and user threads versus kernel threads (green threads, goroutines, virtual threads).
1
Processes, threads and their costs
code
// measured on this machine (Node, Apple M3 Pro, macOS)
spawnSync('/usr/bin/true') × 50 → 1.53 ms average per process (fork/exec + wait)
new Worker(…) start + exit × 20 → 14.6 ms average (OS thread + a new V8 isolate and loop)
// fork / exec / wait in C, the Unix process model in nine lines
pid_t pid = fork(); // two processes return from this call
if (pid == 0) { // child
execlp("ls", "ls", "-l", NULL); // replace the program
_exit(127); // only reached if exec failed
}
int status; waitpid(pid, &status, 0); // parent waits; without this the child becomes a zombieA PROCESS
an address space, one or more threads, and the kernel's record of both
swipe the figure sideways, or tap expand for full screen
1/5
address space
Each process sees its own virtual address space: code, globals, heap, mapped libraries and stacks. Two processes can use the same addresses for different data; page tables keep them apart (part 2).
a private virtual address spacesame addresses, different memory
2
States, context switches and kinds of threads
| state | meaning |
|---|---|
| running | on a CPU now |
| ready (runnable) | waiting for a CPU |
| blocked (sleeping) | waiting for IO, a lock, a timer |
| zombie | exited, but the parent has not collected its status yet |
A context switch saves one thread's registers and loads another's; switching processes also switches page tables, which can flush TLB entries (part 2). Direct costs are microseconds; indirect costs (cold caches) are often larger.
| model | scheduled by | examples |
|---|---|---|
| kernel threads (1:1) | the OS | Java platform threads, pthreads, Rust std threads |
| green / user threads (M:N) | the runtime, onto a few kernel threads | goroutines, Java virtual threads, Erlang processes, Tokio tasks |
| event loop | one thread, callbacks | Node, Nginx, Redis |