Processes and Threads
How the operating system runs many programs, and many paths within one program, at the same time.
What is it?
A process is a running program: its code, its own private memory (the address space), open files, and at least one thread. Two processes can't see each other's memory unless they set up sharing explicitly.
A thread is one path of execution inside a process: an instruction pointer, registers and a stack. All threads in a process share the same heap, globals and open files. That makes communication between threads cheap (just read shared memory) and dangerous (two threads can change the same data at once).
The OS scheduler decides which thread runs on which CPU core and for how long. When it swaps one thread out for another, that's a context switch.
Some runtimes add their own lightweight threads on top: Go's goroutines, Java's virtual threads, Erlang processes. These are called green threads or user-space threads. The runtime multiplexes many of them onto a few OS threads, so you can have hundreds of thousands at once.
Explain like I'm 10
A process is a restaurant kitchen with its own pantry and equipment. Threads are cooks in that kitchen: they share the pantry, so they work together quickly, but two cooks can grab the same pan. Separate processes are separate kitchens; safer, but passing food between them means carrying it across the street.
Examples
Threads share memory; processes don't (Python)
import threading
import multiprocessing
counter = {"value": 0}
def bump():
counter["value"] += 1
thread = threading.Thread(target=bump)
thread.start(); thread.join()
print(counter["value"]) # 1: the thread changed our dict
process = multiprocessing.Process(target=bump)
process.start(); process.join()
print(counter["value"]) # still 1: the child changed its own copyGoroutines: cheap concurrent tasks (Go)
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make([]int, 10_000)
for i := 0; i < 10_000; i++ {
wg.Add(1)
go func(i int) { // 10,000 goroutines, a few OS threads
defer wg.Done()
results[i] = i * i // each writes its own slot: no sharing conflict
}(i)
}
wg.Wait()
fmt.Println(results[9_999])
}Each goroutine starts with a few KB of stack that grows as needed, so ten thousand are cheap. Ten thousand OS threads would each reserve far more memory and strain the scheduler.
How it works
Address spaces. Each process gets a virtual address space. The CPU's MMU translates virtual addresses to physical pages using the process's page tables, so the same address in two processes points to different physical memory. That isolation is what stops one crashing program from corrupting another.
Creating them. On Unix, fork() clones a process (pages are shared copy-on-write until either side writes), and exec() replaces its program. Creating a thread is cheaper: it only needs a new stack and register state in the existing address space.
Context switching. The kernel saves the running thread's registers and instruction pointer, picks another thread, and restores its state. Switching between threads of the same process keeps the same page tables. Switching between processes also changes the address space, which flushes some TLB entries and makes caches colder, so it costs more.
Scheduling. Preemptive schedulers give each runnable thread a time slice and interrupt it with a timer when the slice ends. Threads blocked on I/O or a lock don't get scheduled until they're woken. Linux's scheduler balances fairness and priority across cores.
Green threads (M:N). The runtime schedules M lightweight tasks onto N OS threads. When a goroutine blocks on a channel or network I/O, the Go runtime parks it and runs another on the same OS thread, without a kernel context switch.
Python's GIL. CPython has a Global Interpreter Lock: only one thread executes Python bytecode at a time. Threads still help for I/O-bound work (the lock is released while waiting on I/O), but CPU-bound Python code needs multiprocessing (separate processes, each with its own GIL) or native extensions that release the lock. CPython 3.13+ offers an experimental free-threaded build without the GIL.
Process A (own address space) Process B (own address space)
+------------------------------+ +---------------------------+
| code | globals | heap | | code | globals | heap |
|------------------------------| |---------------------------|
| Thread 1 | Thread 2 | Thread3| | Thread 1 |
| stack | stack | stack | | stack |
+------------------------------+ +---------------------------+
threads share heap separated by the MMU;
talk via pipes, sockets,
shared memory
Green threads (M:N):
g1 g2 g3 g4 g5 g6 ... (goroutines)
\ | / \ | /
OS thread 1 OS thread 2 -> CPU coresWhy does it exist?
Computers run many programs at once, and one program often has several things to do at once: serve many clients, keep a UI responsive while working, use every CPU core. Processes provide isolation so programs can't corrupt each other. Threads provide cheap concurrency inside a program. Green threads exist because OS threads are too heavy to create one per connection at large scale.
When to use it
- Multiple processes for isolation (a browser tab per process, worker processes behind a web server), for crash containment, and for CPU-bound parallelism in GIL languages like Python. - Threads for parallel CPU work over shared data, and for blocking I/O when you don't have an async API. - Goroutines / virtual threads for servers handling many concurrent connections with simple, blocking-style code.
When not to use it
- Don't add threads to a program that is fast enough single-threaded; shared state brings race conditions and much harder debugging. - Don't create one OS thread per request at high concurrency; use a pool, green threads, or async I/O. - Don't use Python threads to speed up CPU-bound pure-Python code; the GIL serializes it. Use processes or a native library. - Don't use more CPU-bound worker threads than cores; extra ones just add context switches.
Common mistakes
Expecting a child process to see changes to the parent's variables (or vice versa). After fork or spawn, each has its own memory.
Using threads in CPython for CPU-heavy work and seeing no speedup because of the GIL.
Creating an unbounded number of OS threads (one per request) and running out of memory or thrashing the scheduler.
Forgetting to join or wait for threads, so the program exits before they finish or results are read too early.
Assuming the OS will run threads in the order they were started. Scheduling order is not guaranteed.
Practice exercises
- Easy:
Write a program that starts 4 threads, each printing its id 5 times. Run it several times and describe how the interleaving changes between runs.
- Medium:
In Python, time a CPU-bound function (e.g. counting primes below 2 million) run 4 times: sequentially, with 4 threads, and with 4 processes. Explain the results in terms of the GIL.
- Hard:
In Go, spawn 100,000 goroutines that each sleep for one second, then do the same with OS threads in C (pthreads) or Java platform threads. Measure memory usage and creation time, and explain the difference.
Interview questions
What is the difference between a process and a thread?
A process is an isolated running program with its own virtual address space and resources. A thread is an execution path inside a process; threads in the same process share memory and file descriptors but each has its own stack and registers. Processes are isolated and heavier; threads are cheap and share state.
What happens during a context switch?
The kernel saves the current thread's CPU registers and instruction pointer, picks the next thread to run, and restores that thread's saved state. If the new thread belongs to another process, the kernel also switches page tables, which invalidates TLB entries and makes caches colder.
Why is a process switch more expensive than a thread switch?
Threads in one process share an address space, so switching between them keeps page tables and the TLB. A process switch changes the address space, invalidating TLB entries (unless tagged) and losing cache locality, on top of saving and restoring registers.
What is copy-on-write in `fork()`?
After fork, parent and child share the same physical pages marked read-only. Only when one of them writes to a page does the kernel copy that page. Forking is therefore cheap even for large processes, especially when the child immediately calls exec.
What are green threads or goroutines, and why use them?
User-space threads scheduled by a language runtime rather than the kernel, multiplexed M:N onto OS threads. They start with small growable stacks and switch without a kernel transition, so you can run hundreds of thousands. When one blocks on I/O, the runtime parks it and runs another.
What is Python's GIL, and how does it affect multithreading?
The Global Interpreter Lock lets only one thread execute Python bytecode at a time in CPython. I/O-bound threads still benefit because the GIL is released while blocked, but CPU-bound threads don't run in parallel. Use multiprocessing, native extensions that release the GIL, or the experimental free-threaded build.
How do processes communicate if they don't share memory?
Through inter-process communication: pipes, Unix domain or network sockets, message queues, signals, files, or explicitly mapped shared memory segments. Message passing is safer; shared memory is faster but needs synchronization.
What is the difference between preemptive and cooperative scheduling?
Preemptive schedulers interrupt a running thread when its time slice ends, so one busy thread can't starve others. Cooperative scheduling only switches when a task yields, which is cheaper but lets a misbehaving task block everyone, as with a CPU-heavy callback on an event loop.
When would you choose multiple processes over multiple threads?
When you need fault isolation (one crash shouldn't take down others), security boundaries, CPU parallelism in a GIL language, or to scale across machines later. Threads win when tasks share large in-memory state and communicate frequently.
How many threads should a thread pool have?
For CPU-bound work, about one per core; more just adds switching. For I/O-bound work, more threads than cores, roughly cores × (1 + wait time / compute time). Measure and tune, and bound the pool so load spikes queue instead of exhausting memory.