Threads vs Processes in Python: Concurrency Trade-offs
System DesignModel answerLast updated
Compare thread-based and process-based concurrency in Python, covering the GIL, memory isolation, and which model fits I/O-bound vs CPU-bound workloads.
Threads vs Processes in Python
Modern applications often need to do several things at once — serve many users simultaneously, preprocess data in parallel, or keep a UI responsive while work happens in the background. Python gives you two primary tools for this: the threading module and the multiprocessing module. Knowing when to reach for each one is a practical engineering skill.
What to address
Part 1 — Core concepts
Explain what distinguishes a thread from a process at the operating system level. Cover:
- How each maps onto physical CPU cores
- How memory is (or isn't) shared between concurrent units of execution
- What the Global Interpreter Lock (GIL) is, why it exists in CPython, and what it actually prevents vs. what it doesn't
Part 2 — Applied scenarios
Walk through the right concurrency strategy for each situation and justify your choice:
- A backend service fielding a large number of simultaneous requests, each of which spends most of its time waiting on a database or external API.
- A data pipeline that applies heavy numerical transformations — say, matrix operations on large arrays using NumPy.
Part 3 — Trade-off analysis
Compare threads and processes across these dimensions:
- Memory and startup overhead
- Cost of context switching
- How the two units communicate and share data
- Fault isolation
Your answer should be concrete: give rough numbers where helpful, call out common mistakes (for example, oversubscribing CPU cores), and mention any modern Python features that change the picture.
Hints
Hint 1
The GIL doesn't affect all Python code equally — think about what happens when a thread is blocked on a network call vs. running a Python for-loop. That distinction drives most of the practical advice here.
Hint 2
NumPy's vectorized operations are a trap for the unwary: matmul and large ufuncs already spin up their own BLAS threads internally. What happens if you wrap that in a process pool with several workers?
Hint 3
Fork, spawn, and forkserver are the three process start methods on Linux/macOS. One of them has a subtle but nasty interaction with threads — consider what state gets copied and what doesn't.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The OS Primitives
A process is an isolated execution environment managed by the OS: it has its own virtual address space, file descriptor table, and at least one thread. A thread lives inside a process and shares its heap, globals, and open files with every sibling thread, while keeping its own stack and register state.
Both threads and processes are scheduled onto CPU cores by the OS. On Linux they are both represented as tasks. A process with four threads can run on four cores simultaneously, and so can four single-threaded processes. The abstraction you choose doesn't determine parallelism — the number of cores does. The exception is a runtime lock that serializes execution, which is exactly what the GIL does.
The GIL in Practice
CPython's Global Interpreter Lock ensures that only one thread executes Python bytecode at any moment. It exists primarily to protect CPython's reference-counted memory management from data races without requiring fine-grained locking on every object.
What this means concretely:
- Pure-Python CPU-bound work gets no parallel speedup from threads. Eight threads on eight cores run about as fast as one thread — you're just paying for context switching on top.
- The GIL is released during blocking I/O,
time.sleep, and inside many C extensions. NumPy's BLAS-backed linear algebra operations, for example, release the GIL during the heavy computation. A thread waiting on a database socket is also GIL-free. - Multiprocessing bypasses the GIL entirely, because each process has its own interpreter with its own lock.
- Python 3.13 introduced an experimental free-threaded build (PEP 703), but the standard CPython release still ships with the GIL.
Scenario 1: Many Concurrent I/O-Bound Requests
Each request is mostly idle — it fires a database query and waits. The GIL is released during that wait, so threads genuinely overlap.
A thread pool of 50–200 threads handles this well and is cheap: threads share the process address space, so each one adds only its stack (reserved at ~8 MB on Linux, committed lazily) plus a kernel task struct. For thousands of simultaneous connections, asyncio with an event loop (e.g., uvicorn + FastAPI) is usually better still — each suspended coroutine costs a few KB, and there are no kernel context switches between pending requests.
Spawning one process per request would be wasteful. A fresh CPython interpreter with imported libraries typically occupies 20–100+ MB, and the startup cost is milliseconds. The bottleneck is waiting on I/O, not CPU, so you gain nothing from the extra isolation.
The standard production pattern is a handful of worker processes (roughly one per core, as with gunicorn workers), each running an async event loop or a thread pool for I/O concurrency. You use cores without wasting memory.
Scenario 2: NumPy-Heavy Data Preprocessing
This is subtler, and it's where many candidates go wrong.
Vectorized NumPy operations (matmul, large elementwise ops) run in C and release the GIL. More importantly, they often use a multithreaded BLAS library (OpenBLAS or MKL) internally. A single Python thread calling np.dot on a large matrix can already saturate all cores through BLAS parallelism.
Wrapping that in a process pool with, say, 8 workers on an 8-core machine means 8 processes × 8 BLAS threads = 64 threads competing for 8 cores. This oversubscription causes thrashing and is usually slower than a single worker. The fix is to cap BLAS threading before spawning workers:
import os
os.environ["OMP_NUM_THREADS"] = "1" # set before importing NumPy
os.environ["MKL_NUM_THREADS"] = "1"
# or use threadpoolctl at runtime
If the pipeline has significant pure-Python logic — per-row parsing, custom augmentation loops — that part is GIL-serialized and multiprocessing is the right tool. When passing large arrays between processes, avoid pickling them across pipes; instead use multiprocessing.shared_memory or memory-mapped files, or have each worker read its own shard from disk.
Trade-off Summary
| Dimension | Threads | Processes |
|---|---|---|
| Startup cost | ~10–100 µs | ~ms (spawn) or copy-on-write fork |
| Memory overhead | Shared address space; only stack per thread | Full interpreter + modules per process (often 20–100 MB) |
| Context switch | Cheaper; no address-space swap | Costlier; TLB flush, cache pressure |
| Communication | Direct shared memory, needs locks | IPC: pickling over queues, or explicit shared memory |
| Fault isolation | One crash or corruption kills all threads | A crashed worker doesn't affect others |
| CPU-bound Python | Serialized by GIL | True parallelism |
Rule of thumb:
- I/O-bound: threads or async.
- CPU-bound pure Python: processes.
- CPU-bound native code that releases the GIL (NumPy, PyTorch): let the library parallelize internally; add processes only after profiling.
- Need crash isolation: processes.
Benchmark Sketch
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def cpu_task(n: int) -> int:
"""Pure-Python loop: holds the GIL throughout."""
total = 0
for i in range(n):
total += i * i
return total
def io_task(seconds: float) -> float:
"""Sleeping releases the GIL, like waiting on a network socket."""
time.sleep(seconds)
return seconds
def benchmark(executor_cls, fn, args, workers: int = 8) -> float:
start = time.perf_counter()
with executor_cls(max_workers=workers) as pool:
list(pool.map(fn, args))
return time.perf_counter() - start
if __name__ == "__main__": # spawn start method requires this guard
cpu_args = [5_000_000] * 8
io_args = [0.5] * 8
print("CPU — threads: ", benchmark(ThreadPoolExecutor, cpu_task, cpu_args))
print("CPU — processes:", benchmark(ProcessPoolExecutor, cpu_task, cpu_args))
print("I/O — threads: ", benchmark(ThreadPoolExecutor, io_task, io_args))
print("I/O — processes:", benchmark(ProcessPoolExecutor, io_task, io_args))
On a multi-core machine: CPU-bound threads take roughly the same time as serial execution; CPU-bound processes scale near-linearly with cores; both approaches finish I/O-bound work in ~0.5 s, but threads get there with far less startup cost.
Common Mistakes to Call Out
- Fork + threads: forking a multithreaded process copies only the calling thread; locks held by other threads in the parent are locked forever in the child, causing deadlocks. Prefer
spawnorforkserveras the start method. - Copy-on-write is not free: CPython's reference counting modifies object headers constantly. Under
fork, those writes dirty pages that were initially shared, gradually increasing per-worker memory. - Picklability: function arguments and return values flowing through a process pool must be picklable. Lambdas, open file handles, and sockets are not.
- GIL ≠ thread safety:
x += 1is multiple bytecodes. The GIL can be released between them, so read-modify-write operations still race. Usethreading.Lockaround shared state.