Processes vs Threads: Trade-offs and When to Use Each
System DesignModel answerLast updated
Explain how OS processes and threads differ in isolation, scheduling, switching cost, communication, failure and security, and justify which to choose for real production services.
You are asked to explain, as you would to a senior engineer, how an operating-system process differs from a thread, and to turn that knowledge into a practical design decision.
Cover each of these areas:
- Memory isolation: what is private and what is shared.
- Resource ownership: which kernel resources belong to a process and which to a thread.
- Scheduling: what the kernel actually schedules, and how user-level threads fit in.
- Context-switch cost: why switching between threads and switching between processes are not equally expensive.
- Communication: inter-process communication (IPC) compared with in-process synchronization.
- Failure isolation: what happens when one unit crashes.
- Security: whether either one provides a trust boundary.
Then answer the design question: in a production system, when would you pick multiple processes, when multiple threads, and when a mix of both? Back your answer with concrete examples, and mention at least a few well-known pitfalls (for example, behavior of fork() in a multithreaded program, or the Python GIL).
A strong answer is structured, presents the differences as consequences of one underlying idea, and weighs trade-offs instead of declaring one option "faster".
Hints
Hint 1
Try to find a single sentence that explains most of the differences: one construct is about isolation, the other is about sharing.
Hint 2
For context-switch cost, think about what changes when the address space changes: page-table root, TLB contents and cache warmth, not merely saved registers.
Hint 3
For the design question, consider the failure domain, the trust level of the code, whether the workload is CPU-bound or I/O-bound, and how large the shared state is. Real systems often combine both.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Processes isolate; threads share.
- A process is the unit of isolation and resource ownership. It has its own virtual address space, file-descriptor table, credentials, working directory, resource limits and signal dispositions.
- A thread is the unit of execution. It has a program counter, registers, a stack, thread-local storage, a signal mask and a thread ID. It lives inside a process and shares everything else with sibling threads.
On Linux both are "tasks" created by clone(). The flags (CLONE_VM, CLONE_FILES, ...) determine what is shared, which is why the two concepts sit on a spectrum.
Nearly every difference below follows from this: sharing an address space makes threads cheap and fast, and also makes them unsafe. Processes pay for their isolation with overhead.
Dimension by dimension
Memory isolation. Processes have separate virtual address spaces and cannot touch each other's memory unless they set up shared mappings. fork() uses copy-on-write, so pages are shared until one side writes. Threads share heap, globals and code; only stacks and TLS are private. Any thread can corrupt any other thread's data through a stray pointer or a race.
Resource ownership. The process owns the address space, fds, PID, uid/gid, cwd and rlimits. The thread owns only its stack, registers, TID, signal mask and TLS. Closing a file in one thread closes it for all.
Scheduling. With 1:1 threading (Linux, Windows, macOS), the kernel schedules threads independently across cores; a single-threaded process is just one schedulable entity. With M:N or user-level threads (goroutines, green threads), a runtime multiplexes many lightweight tasks onto a few kernel threads. This is cheaper but a blocking syscall can stall a carrier thread if the runtime does not compensate.
Context-switch cost. A process switch changes the page-table base (CR3 on x86) and may flush TLB entries; PCID/ASID softens this. The real cost is the cold TLB and caches afterward. A thread switch within the same process keeps the address space, so mostly registers and stack pointers change. Both involve kernel entry and exit, so typical numbers are in the low microseconds, with the process switch visibly worse once cache effects are counted. Say that the saved-register cost is not the main difference.
Communication.
- Processes use explicit IPC: pipes, Unix/TCP sockets, message queues, signals, or shared memory (
mmap,shm_open). Data is normally serialized and copied, costing O(message size) plus syscalls, but the interface is explicit and easy to reason about. Shared-memory IPC approaches thread speed but reintroduces locking issues. - Threads communicate directly through shared memory and coordinate with mutexes, RW locks, condition variables, semaphores and atomics. It is O(1) with no copy, but brings data races, deadlocks, priority inversion and memory-ordering subtleties.
Failure isolation. A segfault or OOM kill in a process takes down only that process; a supervisor can restart it. A fatal fault in any thread kills the whole process, and non-fatal memory corruption can silently poison other threads.
Security. Processes are a real boundary: different users, seccomp filters, namespaces, cgroups, pledge/unveil. Privilege separation (as in OpenSSH) depends on this. Threads share credentials and memory, so one compromised thread means a compromised process.
Creation and footprint. Creating a thread allocates a stack and a task struct. Creating a process builds page tables and an fd table (even with COW), and fork()+exec() is heavier still. A thread stack reserves often 8 MB of virtual memory on Linux, though little is resident. Each process adds page tables, its own heap and runtime overhead. At around 10k concurrent units this matters, which is why thread-per-connection stops scaling and async I/O or pooled workers take over.
Choosing in production
Prefer processes when:
- Fault isolation matters: Chrome's per-site renderer processes, PostgreSQL's backend per connection.
- Running untrusted or multi-tenant code that needs a sandbox.
- You need CPU parallelism in a GIL language (Python
multiprocessing, Gunicorn sync workers). - You want independent restart, deployment and per-unit resource limits.
Prefer threads when:
- Workers need low-latency access to large shared state: in-memory caches, database buffer pools, game world state.
- The work is I/O concurrency inside one trusted service, typically via a thread pool.
- You need fine-grained parallelism on shared data, such as parallel loops in native code.
Hybrids are the norm. Nginx runs a few worker processes, each with an event loop. Gunicorn can run N processes times M threads. Browsers run many processes, each with many threads. The pattern: processes define crash and trust domains and escape the GIL; threads or async give cheap concurrency inside each domain.
Pitfalls interviewers probe
fork()in a multithreaded program. Only the calling thread exists in the child. Locks held by other threads at fork time stay locked forever. Betweenforkandexec, call only async-signal-safe functions, or useposix_spawn.- Signals. A process-directed signal is delivered to an arbitrary thread that has not blocked it. Block signals in workers and use a dedicated handler thread or
signalfd. - Python GIL. CPython threads do not execute bytecode in parallel, so CPU-bound work needs processes or native code that releases the GIL. I/O-bound work is fine with threads. Free-threaded builds (3.13+, experimental) change this.
- False sharing. Threads writing different variables on the same cache line thrash each other's caches; pad or align hot data.
- Thread explosion. Thousands of blocking threads waste memory and scheduler time. Use bounded pools or async I/O.
- Inherited fds. Parent and child share open-file offsets after
fork. UseO_CLOEXECand close what is not needed. - Over-simplifying. Saying "threads are faster" without noting the loss of isolation and the added synchronization risk is the most common weak answer.
Quick demonstration (Python)
import threading, multiprocessing as mp
counter = {"n": 0}
def bump():
counter["n"] += 1
t = threading.Thread(target=bump); t.start(); t.join()
print("after thread:", counter["n"]) # 1: shared memory
p = mp.Process(target=bump); p.start(); p.join()
print("after process:", counter["n"]) # still 1: child changed its own copy
The thread's write is visible to the parent; the child process modifies its own copy-on-write copy, so the parent's value does not change. Getting data back from a process requires explicit IPC (a Queue, Pipe or shared memory).
Summary answer
Processes buy isolation, fault containment and security at the cost of heavier creation, switching and communication. Threads buy cheap sharing and speed at the cost of shared fate and synchronization complexity. Choose based on failure domain, trust level, workload type (CPU vs I/O) and size of shared state, and expect to combine both.