Threads, asyncio, processes, subinterpreters are not a matter of taste but four different answers to two questions: where the load spends its time, and how much data has to be passed. With numbers.
Commit to an output and a reason before you open the answer.
import time
import numpy as np
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
M = np.random.rand(1600, 1600)
def job(_):
return float((M @ M).sum())
def run(Pool, label):
with Pool(max_workers=4) as ex:
list(ex.map(job, range(4))) # warm-up: the pool and the code itself
t0 = time.perf_counter()
list(ex.map(job, range(4)))
print(f"{label}: {time.perf_counter() - t0:.2f} c")
if __name__ == "__main__": # required: ProcessPool imports the module again
run(ThreadPoolExecutor, "threads ")
run(ProcessPoolExecutor, "processes")threads : 0.27 s
processes: 0.48 sProcesses give real parallelism — and lose by a factor of three.import pickle, numpy as np
a = np.random.rand(5_000_000) # 40 MB
# what does a pickle round trip cost?0.358 sSerialization alone. No useful work has been done yet.import asyncio, time
async def call():
await asyncio.sleep(0.010) # instead of a 10 ms network request
async def sequential():
for _ in range(50):
await call()
async def concurrent():
async with asyncio.TaskGroup() as tg:
for _ in range(50):
tg.create_task(call())
async def main():
t0 = time.perf_counter(); await sequential()
print(f"sequentially: {time.perf_counter() - t0:.3f} s")
t0 = time.perf_counter(); await concurrent()
print(f"concurrently: {time.perf_counter() - t0:.3f} s")
asyncio.run(main())sequentially: 0.510 s
concurrently: 0.012 sOne thread, one core, eleven times faster.import time, threading
def work(n=8_000_000):
t = 0
for i in range(n):
t += i
return t
t0 = time.perf_counter(); work(); work()
seq = time.perf_counter() - t0
ths = [threading.Thread(target=work) for _ in range(2)]
t0 = time.perf_counter()
for t in ths: t.start()
for t in ths: t.join()
par = time.perf_counter() - t0
print(f"sequential: {seq:.2f} s")
print(f"two threads: {par:.2f} s")sequential: 0.54 s
two threads: 0.50 sZero gain — and that is not a bug.All four mechanisms were covered in earlier lessons. Here they come together into one decision, and it is decided by two questions, not by trying the options one by one.
The first question: where does the load spend its time? Waiting, in C code that has released the lock, or in bytecode.
The second question: how much data has to be passed between workers? Threads share memory for free, processes through serialization.
Snippet C. Fifty network calls in sequence take the sum of the waits; concurrently, the time of the longest one. One thread, one core, an elevenfold difference.
Threads solve the same task, but each one costs an OS stack and a switch by the kernel: thousands of simultaneous connections on threads are already a problem, on coroutines they are the norm (lesson 14). The threshold is roughly where the count reaches the hundreds.
The limitation is well known: you need asynchronous libraries all the way through. One synchronous call stalls the whole loop.
Snippet A is the most counter-intuitive. Processes give real parallelism with no GIL at all, yet lose to threads by a factor of three. The reason is in snippet B: forty megabytes of data travel through pickle, and the serialization alone costs 0.358 s — more than all the useful work.
| four tasks over a 40 MB array | time |
|---|---|
ThreadPoolExecutor | 0.46 s |
ProcessPoolExecutor | 1.24 s |
The rule that follows: if the work goes into C, start with threads. They share memory for free and get parallelism by releasing the lock (lessons 15 and 19).
Snippet D. Pure Python holds the lock all the time: threads will give nothing, asyncio even less. Processes remain.
But consequence 2 showed that you pay for them with transfer. So processes win when the work per unit of data is large: parsing a big text into a short result, searching through variants over a small input, processing independent files where each process reads its own.
The reverse case — “send a lot, compute a little” — almost always loses. The way around it is not to send the data: shared_memory, memory-mapped files, or processes that read their input independently by path.
Since 3.12 each subinterpreter can have its own lock (PEP 684): parallelism in one process without separate address spaces. Cheaper to start than a process, stronger isolation than a thread.
But objects are not shared between them, exchange goes through channels with serialization, and C extensions have to be ready for it — many are not. So for now the gain over processes is mainly in startup cost, not in data transfer.
| where the time goes | what to use | why |
|---|---|---|
| waiting on the network or disk, hundreds of tasks | asyncio | cheap switching, no OS stacks |
| waiting, but the library is synchronous | threads | the lock is released on I/O |
| computing inside a C extension | threads | the lock is released, memory is shared |
| computing in bytecode, little data | processes | the only real parallelism |
| computing in bytecode, a lot of data | processes + shared_memory or rewrite the hot part in C | serialization eats the gain |
Note that the first question is almost always settled by measurement, not by reasoning: the test from lesson 19 — run it sequentially and in two threads — answers it in a minute.
Mixing is possible and often necessary. An asynchronous service with a process pool for heavy tasks is a normal architecture: loop.run_in_executor connects them. What is bad is not mixing but choosing at random.
fork and threads are incompatible 🕳. A fork from a process with threads leaves locks in the child that were taken by threads that no longer exist. Hence hangs with multiprocessing in a service with threads, and the change of the default start method in newer versions.
The numbers depend on the size of the task. All the measurements here are about specific volumes. On small tasks the overhead of any mechanism outweighs the gain, and the right answer “do not parallelize” is part of the tree too.
Root R3: the reference count and the GIL. The whole tree is a direct consequence of bytecode running under a global lock while memory in a process is shared.
The order in which they appeared explains why there are four options rather than one. Threads were there from the start, together with the lock. multiprocessing was added in 2008 precisely as a way around the GIL — and the price of serialization came with it. asyncio appeared in 2014 to solve a different task: not parallelism but scale in the number of waits. Subinterpreters with a separate lock came in 2023, an attempt to get parallelism without separate address spaces.
So this is not a set of alternatives designed at once, but four workarounds for one limitation, added over fifteen years. Hence the lack of a single API, and the need to choose deliberately.
This is the choice between threads and processes in C, with one added constraint. In C threads share memory and are therefore cheap to exchange data with, processes are isolated and therefore expensive — exactly the same axis. Python adds the GIL to it: threads stop giving parallelism on computational load, but keep it for everything that goes into a system call or a C library.
That is why the intuition familiar from C works only halfway: “threads are cheaper for exchange” stays true and stays the main argument, while “threads give parallelism” is true only outside the interpreter. Hence the counter-intuitive measurement where processes lose by a factor of three: isolation costs serialization, and on large arrays that price is higher than the gain from extra cores.
Asyncio fits this analogy too — it is epoll with one thread, that is, the event model familiar from network servers in C.
Questions that come up on their own if you read closely. The answer is under the question.
Two questions in a row: where the load spends its time, and how much data has to be passed.
| where the time goes | tool | why |
|---|---|---|
| waiting on the network or disk, hundreds of tasks | asyncio | Waiting needs neither the GIL nor an OS thread |
| waiting, but tens of tasks and synchronous code | threads | No need to rewrite for async |
| computing inside a C extension | threads | The GIL is released, memory is shared — 1.9× on two cores |
| computing in pure Python | processes | The only way to occupy several cores |
| computing in Python, a lot of data | processes + shared_memory | Otherwise serialization eats everything |
The second question matters more than it seems. Processes do not share memory, and everything that goes to a worker passes through pickle. The measurement from this lesson: a 40 MB round trip through serialization takes 0.358 s. If the work itself takes 0.1 s, processes lose to the single-threaded version however many cores you give them.
threads: 0.27 s
processes: 0.45 s the same work in numpy, four tasks
Here threads are faster precisely because numpy releases the GIL, while the processes had to pass the data.
Hence the practical rule: processes pay off when there is a lot of computation per unit of data passed. Long computation over a small input — processes. Shipping arrays back and forth for a cheap operation — they will never pay off.
fork dangerous if the process has threads?Because fork copies memory but does not copy threads — and the child is left with locks taken by owners that do not exist.
A thread that held an internal lock of the allocator, the logger or a connection pool at the moment of fork will not appear in the child. The lock, meanwhile, was copied in the “taken” state, and now there is no one to release it. The very first attempt to take it is an eternal wait.
The insidious part is that it does not fail right away and not every time: it depends on what exactly the other thread was doing at the moment of the fork. The symptom is a process that sometimes silently hangs when a worker starts.
That is exactly why in 3.8 macOS was switched to spawn by default, and 3.12 added a DeprecationWarning when forking a multithreaded process; in 3.14 the default on Linux became forkserver.
import multiprocessing as mp
print(mp.get_start_method()) # what is used now
print(mp.get_all_start_methods()) # what is available on this platform
mp.set_start_method("spawn", force=True) # explicit and predictable
Three methods and when to use which. fork — a fast start and a copy of the parent's state, suitable only for a process without threads. spawn — a clean interpreter from scratch: safe, but the start costs more and everything passed must be serializable. forkserver — a compromise: one clean service process is forked in advance, and the workers are forked from it.
The practical conclusion: if the application has even one background thread — and it almost always does, because the logger, metrics and the http client start them — fork must not be used.
Partly, and not soon. They close exactly one gap between threads and processes.
The idea (PEP 554 and PEP 684): several interpreters in one process, each with its own modules, its own globals and — since 3.12 — its own GIL. That means real parallelism across cores without separate processes.
What is gained over processes: a cheaper start, partly shared memory (code, frozen modules), no separate address space — exchange is potentially cheaper.
What is not gained: Python objects still cannot be passed between interpreters — each has its own heap and its own reference counts. Exchange goes through channels with serialization or through shared memory. So the main pain of processes — the price of passing data — remains.
What gets in the way right now: most C extensions do not support several interpreters in one process. A module with global state at the C level (and there are many, historically including numpy) behaves unpredictably when loaded into a second interpreter. It requires moving to multi-phase init (PEP 489), and that is work on the side of each library.
3.13 brought an interpreters module into the standard library, but the ecosystem is catching up slowly.
The practical conclusion for today: processes remain the working answer for CPU-bound Python. Subinterpreters are worth keeping in mind as something that in a few releases may make ProcessPoolExecutor with its serialization unnecessary — but it is too early to make decisions based on them now.
pickle round trip costs 0.358 s on its own. Computing in bytecode — only processes, and there the volume of transfer has to be counted: tasks with a lot of work and little data win, otherwise serialization eats everything. Subinterpreters are a fourth option with a cheap start and weak support from extensions. And the first question is almost always settled by a one-minute measurement, not by reasoning.C++ gives threads and shared memory without a global lock, and correctness rests entirely on the programmer: mutexes, atomics, the memory model. One model instead of four, maximum control, maximum ways to get it wrong. The tree from this lesson degenerates there into a single question — how to synchronize.
Go made goroutines the only mechanism: a preemptive scheduler, real parallelism across cores, channels for exchange. There is nothing to choose from, and that is its strength. The price is a complex runtime, and the fact that logical races remain (the -race detector exists for a reason).
JavaScript is the opposite pole: one thread and an event loop, full stop. The problem of choice does not exist, but there is nowhere to put computational load either, except workers that exchange data through serialization — exactly like processes in Python, with the same price of transfer.
Python ended up in the middle: it has all the options, and therefore it has a problem of choice that the others do not.
ProcessPoolExecutor for “real parallelism” and got three times slowerArray processing did not speed up enough with threads, so processes were brought in. It got worse, and nobody can explain why.
from concurrent.futures import ProcessPoolExecutor
def process_batch(arr): # arr is a 40 MB numpy array
return (arr * arr).sum()
with ProcessPoolExecutor(4) as ex:
results = list(ex.map(process_batch, batches))
| four tasks | time |
|---|---|
| threads | 0.46 s |
| processes | 1.24 s |
The reasoning was right in general and wrong in particular: the GIL really does get in the way of parallelizing bytecode, but there is almost no bytecode here — all the work is inside numpy, which releases the lock. Serialization, on the other hand, appeared: forty megabytes per task, there and back, 0.358 s per round — more than the computation itself.
Review lets it through because replacing one executor with another is a one-line diff with a convincing justification.
The fix is to go back to threads. And if the data really must go to processes, do not send it:
from multiprocessing import shared_memory
import numpy as np
shm = shared_memory.SharedMemory(create=True, size=arr.nbytes)
view = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf)
view[:] = arr[:] # once
# child processes open shm by name — no copying
This works precisely on the buffer protocol from lesson 15: numpy builds an array on top of someone else's memory. The rule: before reaching for processes, count the volume of transfer and compare it with the volume of work.
Instead of arguing about whether parallelism will help — a short test that points straight to a branch of the tree.
import time, threading
from concurrent.futures import ProcessPoolExecutor
def probe(fn, arg, n=4):
t = time.perf_counter()
for _ in range(n): fn(arg)
seq = time.perf_counter() - t
th = [threading.Thread(target=fn, args=(arg,)) for _ in range(n)]
t = time.perf_counter()
for x in th: x.start()
for x in th: x.join()
thr = time.perf_counter() - t
t = time.perf_counter()
with ProcessPoolExecutor(n) as ex: list(ex.map(fn, [arg]*n))
prc = time.perf_counter() - t
print(f"sequential {seq:.2f} | threads {thr:.2f} ({seq/thr:.1f}×) "
f"| processes {prc:.2f} ({seq/prc:.1f}×)")
How to read the result. Threads sped it up — take threads, question closed. Threads did not, processes did — the work is in bytecode; take processes and check the volume of transfer. Nothing sped it up — either the task is too small for the overhead, or it is not bound by the processor.
What must be checked before drawing conclusions: the task must be large enough, otherwise you are measuring overhead; and it must be the same as in production — on a synthetic test numpy releases the lock, but on your combination of operations it may not.
A separate branch the test will not show: if the load is hundreds of simultaneous waits, neither threads nor processes scale with the number of tasks, and the right answer is asyncio. This case is visible not from a measurement but from the problem statement.
Run the snippets and check them against your prediction. Then:
import multiprocessing as mp
print(mp.get_start_method())
print(mp.get_all_start_methods())
# What is the default on your system? How does spawn differ from fork in start cost?
import os, threading
def t():
import time; time.sleep(5)
threading.Thread(target=t).start()
pid = os.fork()
# Why must you not do this? What happens to the locks in the child?
from concurrent.futures import ThreadPoolExecutor
import time
def io_task(_): time.sleep(0.1)
# Run 100 tasks in a pool of 4 and of 50 workers. Where does it stop being useful?
import sys
print(sys.version_info >= (3, 12))
# On 3.12+ look at the _xxsubinterpreters module — what does starting a subinterpreter cost?
The third question is more practical than the others: on I/O the number of workers can be raised far beyond the number of cores, and knowing exactly where it stops helping is half of tuning any pool.
Lib/concurrent/futures/thread.py and Lib/concurrent/futures/process.py. Worth reading both in a row: the interface is the same, the internals are fundamentally different. A thread takes a task from a queue in shared memory; a process serializes the arguments, sends them into a pipe, and receives the result back. The whole price from consequence 2 is visible in that difference.
Note how the process version handles the case where an argument does not pickle: the error message comes not from the child process but from the parent, when it tries to send. Hence the mysterious PicklingError on lambdas and local classes (lesson 06).
Lib/multiprocessing/shared_memory.py. A thin wrapper over a system call that exports a buffer. Everything else is done by the buffer protocol — the same mechanism that connects numpy with torch.
Lib/asyncio/base_events.py, the run_in_executor method. The bridge between the models: it lets an asynchronous service hand blocking work to a pool of threads or processes. Three lines that lift the limitation from lesson 14.
From L1 you know the tree. Here: the orders of magnitude it is computed with.
| mechanism | starting a worker | switching | passing data |
|---|---|---|---|
| coroutine | microseconds | tens of nanoseconds | free, shared memory |
| thread | tens of microseconds | microseconds, through the kernel | free, shared memory |
| process | tens of milliseconds | microseconds | serialization: 0.358 s for 40 MB |
| subinterpreter | milliseconds | microseconds | serialization through channels |
Hence the practical thresholds. A thread pool makes sense for tasks from a millisecond up; on smaller ones the overhead eats the gain. A process pool — from tens of milliseconds of work per task, and only if there is little data. Coroutines pay off almost always when there is waiting.
On how a process is started. fork is cheap because it copies the address space lazily — but it is incompatible with threads and inherits all of the parent's state, including open connections. spawn starts the interpreter afresh and imports the main module (lesson 17, hence the need for if __name__), so it costs more but is predictable. The default has changed between versions and platforms — check get_start_method, not your memory.
import multiprocessing as mp
print((mp.get_start_method(), mp.get_all_start_methods()))
# → on Linux usually 'fork' and a list of three; on macOS 'spawn'
Tag v3.11.15.
Lib/concurrent/futures/process.py — the whole pipeline: serialization, queues, worker management. You can see exactly where the price from consequence 2 is paid.Lib/multiprocessing/context.py — the start methods and how they differ.Modules/_threadmodule.c — low-level threads and synchronization primitives.Lib/concurrent/futures/process.py — read in full, together with the thread version. The same interface over different models is the best illustration of the lesson.concurrent.futures documentation — selectively: how the executors differ and the restrictions on arguments.