Skip to main content

Processes & Threads

Learning objectives
  • Explain what a process and a thread own, and what a context switch actually costs
  • Describe the Linux address-space layout and how fork/exec/copy-on-write work
  • Map Go's GMP scheduler onto kernel threads and explain why goroutines are cheap
  • Reason about syscalls, signals and process states when debugging production services
  • Design graceful shutdown for a payment service running as PID 1 in a Kubernetes pod

TL;DR​

  • A process is an isolated address space plus resources (file descriptors, credentials, signal handlers); a thread is a schedulable execution context inside it. On Linux both are task_structs created by clone() with different sharing flags.
  • fork() is cheap because of copy-on-write, but its cost still grows with page-table size; memory can balloon when the child or parent writes heavily (Redis BGSAVE).
  • A thread context switch costs roughly microseconds once cache/TLB effects are included; a goroutine switch is roughly 10× cheaper because it stays in user space.
  • Go uses M:N scheduling (GMP): many goroutines (G) multiplexed onto OS threads (M) through logical processors (P, count = GOMAXPROCS). Network I/O parks goroutines on the netpoller; blocking syscalls hand the P to another thread.
  • Syscalls are the boundary between your code and the kernel; each one is a mode switch, so batching (bigger buffers, writev, fewer small writes) matters at high QPS.
  • SIGTERM is a request, SIGKILL is not. In Kubernetes you get SIGTERM, then SIGKILL after terminationGracePeriodSeconds (default 30 s). Exit code 137 = killed by SIGKILL (often OOM), 143 = SIGTERM.

Why it matters​

Consider a bank's transfer API during a rolling deploy at 10:00 on payday. Each old pod gets SIGTERM while it still has in-flight transfers that have debited one account but not yet published the credit event. If the process ignores the signal (because a shell wrapper is PID 1 and never forwards it) the kubelet SIGKILLs it 30 seconds later, mid-transaction. Your idempotency and outbox design (see Transactional Outbox & CDC) saves correctness, but customers still see timeouts, and reconciliation has work to do.

On the e-commerce side, a flash-sale checkout service that uses one OS thread per request runs out of memory or drowns in context switches long before the CPU is busy. Go's goroutine model avoids this, but only if you understand when the runtime does create extra threads (blocking syscalls, cgo, disk I/O) and how GOMAXPROCS interacts with container CPU limits.

Interviewers ask "process vs thread" to check fundamentals, then push on: why goroutines are cheaper, what happens on fork, how you would shut down safely, and what exit code 137 means. These are everyday production questions.

Core concepts​

Process vs thread​

ResourceShared between threads of one process?Notes
Virtual address space (code, heap, globals, mmaps)YesThis is why threads can race on memory
StackNo — one per threadLinux default 8 MiB virtual for pthreads; only touched pages are resident
Registers, program counterNoSaved/restored on context switch
File descriptor tableYesClosing an fd in one thread closes it for all
Signal handlersYesSignal masks are per thread
PIDShared TGIDEach thread has its own TID; getpid() returns the TGID
Credentials, cwd, rlimitsYes (by default)

Linux has no separate "thread" object. fork() and pthread_create() both end up in clone(). A thread is a task created with CLONE_VM | CLONE_FILES | CLONE_FS | CLONE_SIGHAND | CLONE_THREAD; a process is a task that shares (almost) nothing. That is also how containers work: clone() with CLONE_NEW* flags puts the new task in new namespaces (see Linux Containers).

You can see threads directly: ls /proc/$(pgrep myservice)/task lists one directory per thread, and ps -T -p PID shows them with their TIDs.

Address space layout​

Every process sees a private virtual address space. On x86-64 with 4-level paging, user space is 128 TiB (47 bits); the kernel lives in the upper half and is unreachable from user mode.

Notes that matter in practice:

  • Go does not use brk. The runtime reserves heap arenas with mmap and manages them itself; goroutine stacks are also allocated from runtime-managed memory, not from per-thread OS stacks.
  • ASLR randomises the base addresses, which is why stack traces from perf need symbolisation per process.
  • VSZ vs RSS: virtual size counts reserved address space (Go binaries often show large VSZ); resident set size counts pages actually in RAM. Alert on RSS and cgroup memory, never VSZ. Details in Memory Management.

fork, exec, wait — and copy-on-write​

The Unix process model is two calls: fork() duplicates the caller, exec() replaces the current program image with a new binary. The parent wait()s to collect the child's exit status.

  • Copy-on-write (COW): fork() does not copy memory. It copies page tables and marks all writable pages read-only in both processes. The first write to a page triggers a page fault and the kernel copies just that page.
  • fork is not free: copying page tables for a 30 GiB process takes noticeable time (tens to hundreds of milliseconds, roughly) and the parent is paused. Redis logs this as latest_fork_usec. During a heavy write workload, COW can double resident memory in the worst case — the reason Redis docs recommend vm.overcommit_memory = 1 and disabling transparent huge pages (a 2 MiB COW copy per 1-byte write).
  • exec closes O_CLOEXEC descriptors. Go opens every fd with close-on-exec, so children launched with os/exec do not inherit your database sockets by accident.
  • Go never exposes plain fork(). Forking a multi-threaded runtime would leave the child with one thread and locks possibly held by threads that no longer exist. os/exec uses a combined fork+exec path (on Linux a vfork-style clone) so the child immediately becomes another program.

Process states​

  • R (runnable/running), S (interruptible sleep — most idle server threads), D (uninterruptible, usually disk or NFS I/O; cannot be killed until the I/O returns), Z (zombie: exited, waiting for the parent to reap it).
  • Tasks in D count toward Linux load average, which is why a hung NFS mount gives a load of 200 on an idle box (see CPU Scheduling).
  • Zombies and orphans: an orphaned child is re-parented to PID 1 (or the nearest "subreaper"). PID 1 must call wait() on them, or zombies accumulate and eventually exhaust the PID limit. In a container your process may be PID 1.

Kernel threads vs user threads​

ModelMappingExamplesTrade-off
1:1One user thread per kernel threadLinux NPTL pthreads, classic Java threadsSimple and truly parallel, but each thread costs a kernel task, a large stack and kernel-mediated switches
N:1Many user threads on one kernel threadEarly green threads, single-threaded event loopsVery cheap switches, but no parallelism and one blocking syscall stalls everything
M:NMany user threads on a pool of kernel threadsGo goroutines, Erlang processes, Java virtual threads (Java 21+)Cheap and parallel, but the runtime must handle blocking syscalls, preemption and fairness itself

Go's GMP model​

  • G — a goroutine: a small struct plus a growable stack (minimum 2 KiB; since Go 1.19 the runtime may start larger based on observed average usage). Stacks grow by copying, up to 1 GB on 64-bit by default.
  • M — a machine: an OS thread. The runtime creates them on demand; the default cap is 10,000 (debug.SetMaxThreads), and exceeding it crashes the program.
  • P — a logical processor that holds a local run queue (up to 256 Gs plus a runnext slot) and the memory-allocator cache. Exactly GOMAXPROCS Ps exist, so at most GOMAXPROCS goroutines run Go code simultaneously.

How it behaves:

  1. Scheduling decisions happen in user space. When a goroutine blocks on a channel, mutex or network read, the runtime parks it and runs another G on the same M — no kernel involvement, so a switch costs on the order of a hundred nanoseconds (rough).
  2. Network I/O goes through the netpoller: sockets are non-blocking; on EAGAIN the goroutine parks and epoll wakes it later. Thousands of idle connections cost goroutine stacks and buffers, not threads. See I/O Models.
  3. Blocking syscalls (file reads, fsync, cgo calls) block the M. The runtime detaches the P; if the syscall lasts longer than roughly 20 µs, the sysmon background thread hands the P to another M so other goroutines keep running. This is why disk-heavy Go programs show many threads.
  4. Work stealing: an idle P steals half the run queue of a busy P; the global queue is checked periodically for fairness.
  5. Preemption: since Go 1.14 the runtime can asynchronously preempt a goroutine in a tight loop by sending its thread a signal (SIGURG). Before that, a loop without function calls could stall GC.

Deep dive on the Go side: Goroutines & Channels.

Context switch cost​

A kernel context switch saves registers, switches kernel stacks, possibly switches page tables (process switch), and runs scheduler logic. The direct cost is roughly 1–2 µs on modern hardware; the indirect cost — cold L1/L2 caches, TLB misses after switching address spaces, branch predictor pollution — often dominates and depends on working-set size. Threads of the same process skip the page-table switch, so they are cheaper than process switches.

Signals of trouble: vmstat 1 showing hundreds of thousands of cs per second, pidstat -w showing high nvcswch/s (involuntary switches = preempted while still wanting CPU, typical of CPU throttling or oversubscription).

System calls​

A syscall is a controlled entry into the kernel: arguments go in registers, the syscall instruction switches to kernel mode, the kernel validates and runs the handler, then returns a value or -errno.

  • A trivial syscall costs on the order of 100 ns to a few hundred ns; Meltdown mitigations (KPTI) made syscall-heavy workloads noticeably slower on affected CPUs.
  • vDSO: clock_gettime and gettimeofday are served from a kernel-provided page mapped into your process, so time.Now() in Go usually does not enter the kernel.
  • Practical lesson: writing a log line or a response in many small write() calls multiplies syscalls. Use bufio.Writer, batch Kafka messages, and prefer writev-style APIs (Go's net.Buffers).

Signals​

SignalNumberCatchableTypical meaning for a service
SIGTERM15Yes"Please shut down" — Kubernetes, systemd, docker stop
SIGINT2YesCtrl-C in a terminal
SIGKILL9NoImmediate death: grace period expired or OOM killer
SIGHUP1YesOften "reload config" by convention
SIGQUIT3YesGo's default handler dumps all goroutine stacks and exits — handy for hung processes
SIGPIPE13YesWrite to a closed pipe/socket; Go returns EPIPE for sockets instead of dying
SIGCHLD17YesA child changed state; the parent should wait()

Exit codes above 128 mean "killed by signal (code − 128)": 137 = SIGKILL, 143 = SIGTERM. Kubernetes shows OOMKilled when the 137 came from the memory cgroup.

PID 1 is special. Inside a PID namespace the kernel does not apply the default action of a signal to PID 1 unless PID 1 installed a handler. The Go runtime installs handlers, so a Go binary as PID 1 exits on SIGTERM — but if your Dockerfile uses the shell form (ENTRYPOINT ./app instead of ENTRYPOINT ["./app"]), /bin/sh becomes PID 1 and does not forward signals. Your app never hears SIGTERM and is SIGKILLed after the grace period. Use the exec form, or a tiny init such as tini (docker run --init) when you spawn child processes that need reaping.

Graceful shutdown in Kubernetes​

Endpoint removal is asynchronous, so for a few seconds after SIGTERM, traffic may still arrive. A short preStop sleep (or a sleep at the start of your shutdown handler) lets load balancers catch up before you stop accepting connections. The grace period includes the preStop time.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Multi-process (prefork, one process per worker)Strong isolation; a crash or memory leak kills one worker; simple mental modelHigher memory per worker; IPC needed to share state; fork costLanguages with a GIL (Python, Ruby), or untrusted plugins
Thread-per-request (1:1)Straightforward blocking code; true parallelismMemory and scheduler overhead at thousands of concurrent requests; context-switch heavyModerate concurrency, CPU-bound work, legacy Java/C++ services
Goroutines / virtual threads (M:N)Blocking-style code with event-loop scalability; cheap creationRuntime complexity; hidden thread creation on blocking syscalls/cgo; easy to leak goroutinesMost networked backend services — the Go default
Single-threaded event loop (N:1)No locks; very predictable; low memoryOne slow callback stalls everything; needs multiple processes for multi-coreRedis-style in-memory servers, proxies, Node.js

In practice​

A graceful shutdown skeleton for an HTTP service:

package main

import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()

mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}

go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()

<-ctx.Done()
stop() // restore default handling: a second SIGTERM kills immediately
log.Println("SIGTERM received, draining")

// Let endpoint removal propagate before refusing new connections.
time.Sleep(5 * time.Second)

shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
// Then: stop Kafka consumers (commit offsets), flush producers, close DB pools.
}

Budget the timeline explicitly: 5 s propagation + 20 s drain must fit within terminationGracePeriodSeconds (30 s default) with margin. For long-running work (batch settlement jobs, Kafka consumers mid-batch) either raise the grace period or make the work resumable and idempotent.

Useful inspection commands:

# Threads of a process and their states
ps -L -o pid,tid,stat,comm -p "$(pgrep -n payments)"
# Voluntary vs involuntary context switches per thread
pidstat -wt -p "$(pgrep -n payments)" 1
# Signal masks and handlers (SigCgt = caught signals bitmap)
grep -E 'Threads|SigCgt|voluntary' /proc/"$(pgrep -n payments)"/status
# Dump goroutine stacks of a hung Go process (it will exit afterwards)
kill -QUIT "$(pgrep -n payments)"

Rough numbers to keep in your head (all approximate, hardware-dependent): goroutine creation ≈ sub-microsecond and a few KiB; OS thread creation ≈ tens of microseconds and a kernel task plus stack; kernel context switch ≈ 1–5 µs including cache effects; trivial syscall ≈ 0.1–0.5 µs.

Common pitfalls​

  • Shell-form ENTRYPOINT. sh is PID 1, SIGTERM never reaches the app, every deploy ends in SIGKILL after 30 s and in-flight requests fail. Symptom: deploys are slow and logs never show "shutting down".
  • No drain delay. The app stops accepting connections the instant it gets SIGTERM while the load balancer still routes to it. Symptom: a burst of 502/503 on every rollout.
  • Goroutine leaks. Goroutines blocked forever on a channel or a missing ctx cancellation. Symptom: goroutine count and RSS climb steadily; /debug/pprof/goroutine shows thousands parked on the same line.
  • Thread explosion from blocking calls. Thousands of goroutines doing synchronous file I/O or slow cgo calls each pin an M. Symptom: runtime: program exceeds 10000-thread limit or high memory with low heap usage.
  • Zombie accumulation. A service that shells out (exec of openssl, pg_dump) as PID 1 and leaks grandchildren. Symptom: ps shows Z entries; eventually fork: retry: Resource temporarily unavailable once pids.max is hit.
  • Forking a large process. Snapshotting (Redis BGSAVE, some backup agents) on a 50 GiB process with THP enabled causes latency spikes and memory blow-up. Symptom: p99 spikes aligned with snapshots; OOM kills during persistence.
  • Misreading exit code 137 as "the app crashed". It means SIGKILL — check OOMKilled and grace-period expiry first.

Interview angle​

  • "Process vs thread?" A strong answer goes beyond "threads share memory": what exactly is shared (address space, fds, signal handlers) vs per-thread (stack, registers, signal mask), that Linux implements both via clone(), and the cost implications (creation, switching, isolation).
  • "Why are goroutines cheaper than threads?" Small growable stacks, user-space scheduling (no kernel transition on park/unpark), and the netpoller turning blocking I/O into parked goroutines. Mention the caveats: blocking syscalls and cgo still consume threads; GOMAXPROCS bounds parallelism.
  • Follow-ups to expect: what happens on fork in a multi-threaded program; what COW is; how Go handles a goroutine stuck in a tight loop (async preemption); how you would design graceful shutdown; what 137 vs 143 means.
  • Red flags: saying threads have separate heaps; believing SIGKILL can be caught; not knowing that Kubernetes sends SIGTERM first; claiming goroutines map 1:1 to OS threads.

Self-check​

1. A teammate says "threads are just lightweight processes on Linux". In what sense is that true, and what is the practical difference?

True in implementation: both are tasks created by clone(), scheduled identically by the kernel. The difference is the sharing flags: threads share the address space, file descriptor table and signal handlers; processes get their own (with COW memory). Practically, threads can race on shared memory and one thread's crash (e.g. a segfault) kills the whole process, while processes are isolated and need IPC to share data.

2. Why does Redis' BGSAVE sometimes double memory usage and cause latency spikes?

fork() copies page tables (pausing the parent for a time proportional to memory size) and then relies on copy-on-write. Every page the parent modifies during the snapshot gets duplicated. Under write-heavy load most pages may be touched, approaching 2× memory. With transparent huge pages, each small write copies 2 MiB instead of 4 KiB, making both memory growth and fault latency worse.

3. Walk through what the Go runtime does when a goroutine calls os.ReadFile on a slow network-attached disk.

Regular files are not pollable by epoll, so the read is a blocking syscall on the current M. The runtime marks the goroutine as in-syscall and detaches its P. If the syscall exceeds roughly 20 µs, sysmon hands the P to another (possibly new) M so other goroutines continue. When the read returns, the original M tries to reacquire a P; if none is free, the goroutine goes to a run queue and the M parks. Many concurrent slow reads therefore create many threads.

4. Your pods take exactly 30 seconds to terminate on every deploy and some requests fail. What do you check?

The 30 s matches the default grace period, so SIGTERM is probably not handled: check whether PID 1 is a shell (ps -o pid,comm inside the container), whether the Dockerfile uses shell-form ENTRYPOINT, and whether the app registers a SIGTERM handler. For the failed requests, check whether the app stops accepting before endpoints are removed (add a preStop or in-app drain delay) and whether Shutdown has a timeout shorter than the remaining grace period.

5. What is the difference between a voluntary and an involuntary context switch, and what does a high involuntary rate suggest?

Voluntary: the thread blocked (I/O, lock, sleep) and gave up the CPU. Involuntary: the scheduler preempted it while it was still runnable (time slice expired or a higher-priority task woke). A high involuntary rate suggests CPU contention — more runnable threads than CPUs, CFS quota throttling in a container, or a GOMAXPROCS larger than the CPU allowance.

6. Why does Go not provide a plain fork() call?

The Go runtime is always multi-threaded (scheduler threads, GC workers, sysmon). After fork(), only the calling thread exists in the child, but locks held by other threads at fork time remain locked forever, and runtime state is inconsistent. So Go only supports fork immediately followed by exec (os/exec, syscall.ForkExec), where the child replaces itself before touching runtime state.

7. A pod shows exit code 137 but Kubernetes does not say OOMKilled. What are the likely causes?

137 means SIGKILL. Without OOMKilled, likely causes are: the grace period expired after SIGTERM (the app did not exit in time), a liveness probe failure leading to a kill after the grace period, a manual kill -9, or a node-level OOM kill that hit a process inside the container but not the container's main cgroup event. Check events (kubectl describe pod), the previous container's logs, and dmesg on the node.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Observe threads, goroutines and signals on a real Linux box (a VM or docker run --rm -it golang:1.25 works).

  1. Write a Go program that starts 10,000 goroutines that each time.Sleep(time.Minute), plus one HTTP server with net/http/pprof imported. Check ls /proc/PID/task | wc -l (thread count) and the goroutine count at /debug/pprof/goroutine?debug=1. Explain why threads stay in the low tens.
  2. Change the goroutines to each os.ReadFile a large file on a slow volume in a loop (or call syscall.Syscall on a blocking read from a FIFO with no writer). Watch the thread count climb and explain via the GMP handoff rule.
  3. Add the graceful shutdown code above. Run it in a container twice: once with ENTRYPOINT ["/app"], once with ENTRYPOINT /app. Run docker stop and time it; inspect the exit codes with docker inspect -f '{{.State.ExitCode}}'.
  4. Send kill -QUIT to the running program and read the goroutine dump.

Done looks like: a short note with thread counts for steps 1–2, stop times and exit codes for both ENTRYPOINT forms, and one sentence explaining each result.

Further reading​

Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).