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 zombie
A PROCESS
an address space, one or more threads, and the kernel's record of both
text (code)read-only, shared between processes running the same programdata + BSSglobalsheapgrows up: malloc, the managed runtime heapmapped regionsshared libraries, mmap'd filesstacksone per thread, grows downkernel: process control blockpid, state, registers, page table, open files, credentials
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

statemeaning
runningon a CPU now
ready (runnable)waiting for a CPU
blocked (sleeping)waiting for IO, a lock, a timer
zombieexited, 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.

modelscheduled byexamples
kernel threads (1:1)the OSJava platform threads, pthreads, Rust std threads
green / user threads (M:N)the runtime, onto a few kernel threadsgoroutines, Java virtual threads, Erlang processes, Tokio tasks
event loopone thread, callbacksNode, Nginx, Redis