Sub topic 9
Choosing between threads, processes, and asyncio
This chapter assumes you can write Python functions and use with statements. It also assumes you have seen ThreadPoolExecutor and ProcessPoolExecutor and know what the GIL is. The earlier chapters explained how each tool works. This one covers how to pick one for a workload and how to check that the pick was right.
Start with the bottleneck, not the tool
The choice depends on what your program spends its time doing. Ask these questions in order:
- Is the program slow because it waits (network, disk, a database, a subprocess), or because it computes?
- If it waits, how many things wait at once? Ten, or ten thousand?
- If it computes, is the work done in pure Python, or inside a native library that releases the GIL?
- How much data does each task need, and how much does it return?
Each answer points toward one model. The sections below cover them in turn.
Waiting work: threads or asyncio
A thread blocked on a socket or on time.sleep releases the GIL. Other threads then run, so waits overlap. Both threads and asyncio give you that overlap. They differ in cost and in how they switch tasks.
- Threads are preemptive. The interpreter can switch between them between bytecode instructions. You can call ordinary blocking libraries such as
requestsor a database driver. Any shared mutable state needs locks. - asyncio is cooperative. A task runs until it reaches an
await, and only then can another task run. Because switches happen only atawait, shared state is easier to reason about. It only works with libraries that have async APIs, and one blocking call stalls every task.
Each OS thread costs memory for its stack and scheduling work. A few hundred threads is usually fine. Tens of thousands is not. An asyncio task is a small Python object, so tens of thousands of concurrent connections are practical.
A rule of thumb:
- Use threads for tens of concurrent waits, or when you depend on blocking libraries.
- Use asyncio for thousands of concurrent waits, or when the whole stack is already async.
If you have blocking code inside an asyncio program, asyncio.to_thread(func, *args) runs it in a worker thread without freezing the event loop.
Computing work: processes, unless the GIL is released
In a standard GIL build, two threads cannot run pure-Python bytecode at the same time. CPU-bound threads therefore give no speedup, and they can be slightly slower than a plain loop because of switching overhead. Separate processes each have their own interpreter and their own GIL, so they run on separate cores.
Processes are not free:
- Startup cost. Each worker is a new interpreter. With
spawn, it re-imports your modules. - Pickling cost. Arguments and results cross the process boundary as pickled bytes. A task that receives a 200 MB list and returns a small number spends most of its time serializing.
- Memory cost. Each process has its own memory. Sharing is explicit (queues, pipes, shared memory), not automatic.
- Restrictions. Arguments, results, and the target function must be picklable. Lambdas and locally defined functions are not.
The rule is to give each process a large chunk of computation and a small amount of data. A task that takes 5 ms to compute but needs 50 ms to pickle gets slower in a process pool.
There is one exception to "CPU-bound means processes". Many native libraries release the GIL while they run long operations, including NumPy for large array operations, hashlib on large buffers, zlib, and many image and database libraries. Threads can then use several cores for that work. This varies by library and by operation, so check the library's documentation and measure.
Summary table
| Workload | Best first choice | Why | Main risk |
|---|---|---|---|
| Tens of blocking calls (HTTP, DB) | Threads | Blocking calls release the GIL, and existing libraries work unchanged | Races on shared state |
| Thousands of concurrent connections | asyncio | Tasks are cheap, and switching happens only at `await` | One blocking call stalls everything |
| Pure-Python number crunching | Processes | Each process has its own GIL | Pickling and startup cost |
| Large array or compression work in a GIL-releasing library | Threads | Parallel without copying data | Library may hold the GIL in some operations |
| Mixed: fetch pages, then parse them heavily | Async or threads for fetching, process pool for parsing | Each stage matches its bottleneck | More moving parts |
Measure it
A choice is a hypothesis until you time it. The harness below runs the same workloads serially, with a thread pool, with a process pool, and with asyncio. Run it on your own machine, because core count and operating system change the numbers.
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def io_task(n):
time.sleep(0.5) # stands in for waiting on the network
return n
def cpu_task(n):
total = 0
for i in range(n):
total += i * i
return total
async def async_io_task(n):
await asyncio.sleep(0.5)
return n
async def run_async(args):
return await asyncio.gather(*(async_io_task(a) for a in args))
def timed(label, fn):
start = time.perf_counter()
fn()
print(f"{label:<26}{time.perf_counter() - start:.2f}s")
def serial(task, args):
for a in args:
task(a)
def pooled(pool_cls, task, args, workers=4):
with pool_cls(max_workers=workers) as pool:
list(pool.map(task, args))
if __name__ == "__main__":
io_args = list(range(8))
cpu_args = [3_000_000] * 4
print("I/O-bound, 8 tasks of 0.5s")
timed("serial", lambda: serial(io_task, io_args))
timed("threads (4 workers)", lambda: pooled(ThreadPoolExecutor, io_task, io_args))
timed("processes (4 workers)", lambda: pooled(ProcessPoolExecutor, io_task, io_args))
timed("asyncio", lambda: asyncio.run(run_async(io_args)))
print("CPU-bound, 4 tasks")
timed("serial", lambda: serial(cpu_task, cpu_args))
timed("threads (4 workers)", lambda: pooled(ThreadPoolExecutor, cpu_task, cpu_args))
timed("processes (4 workers)", lambda: pooled(ProcessPoolExecutor, cpu_task, cpu_args))On a typical multi-core machine with a standard GIL build, expect results close to this:
- I/O-bound: serial takes about 4 s, threads about 1 s (eight waits in two rounds of four), asyncio about 0.5 s (all eight overlap), and processes about 1 s plus startup.
- CPU-bound: threads are about as slow as serial, or slower. Processes are noticeably faster if you have at least four free cores.
The measurement practices matter as much as the code:
- Use
time.perf_counter(), nottime.time(), for durations. - Always keep a serial baseline. Without it you cannot tell whether concurrency helped.
- Use realistic task sizes and data. A toy payload hides pickling cost.
- Repeat the run a few times and use the median. Other programs on the machine add noise.
- Vary the worker count. Speedup usually flattens once workers exceed physical cores (for CPU work) or once the remote service becomes the limit (for I/O work).
Combining models
Real programs often have both kinds of work. Common patterns:
- Async front, process pool behind. An asyncio server handles connections. CPU-heavy steps go to a
ProcessPoolExecutorthroughloop.run_in_executor, so the event loop stays responsive. - Threads for I/O, processes for compute. A thread pool downloads files. A process pool parses them. Queues or futures connect the two stages.
- Threads around a native library. Ordinary threads call into array or compression code that releases the GIL. No process machinery is needed.
Keep the combination as simple as the measurements allow. Each extra layer adds failure modes: exceptions that cross process boundaries, shutdown ordering, and harder debugging.
Common mistakes
- Using threads for pure-Python CPU work and wondering why four threads take as long as one.
- Using a process pool for tiny tasks. If one task takes microseconds, pickling and scheduling dominate. Batch the work with the
chunksizeargument ofpool.map, or give each task a bigger slice of data. - Calling blocking code inside
async def.time.sleepor a synchronous HTTP request in a coroutine stalls the whole event loop. Use the async equivalent, orasyncio.to_thread. - Oversizing the pool. More workers than cores does not speed up CPU work. More threads than the remote server tolerates can trigger rate limits or errors.
- Forgetting the
__main__guard when using processes, which causes errors or recursive worker spawning underspawn. - Skipping measurement because the model "should" be faster.
Free-threaded builds change the CPU-bound answer
Python 3.13 and later offer an experimental free-threaded build that can run without the GIL. On that build, CPU-bound pure-Python threads can use several cores, which removes the main reason to prefer processes for shared-memory work. The details are still changing, and many packages do not yet support it. Treat the rules in this chapter as the default for standard builds, and re-measure if you deploy on a free-threaded interpreter.
Exercise
A service must resize 2,000 large JPEG files, with each resize taking about 300 ms of computation in pure Python, on an 8-core machine. A colleague proposes a ThreadPoolExecutor with 8 workers. What would you choose instead, how would you set it up to limit overhead, and how would you check your choice?
Show answer
Use a ProcessPoolExecutor with about 8 workers, because the work is pure-Python CPU-bound and threads would share one GIL. To limit pickling overhead, pass file paths to the workers and let each worker read and write the files itself, instead of sending image bytes through the pool. Use pool.map with a chunksize greater than 1 to cut scheduling overhead. To check the choice, time a serial run on a sample of the files, then the thread pool and the process pool on the same sample using time.perf_counter(), and compare medians over several runs. Also try different worker counts, since speedup should flatten near the number of physical cores.
Exercise
An async web crawler written with asyncio sometimes freezes for two seconds at a time, and all in-flight requests stall together. A profile shows that each frozen period matches a call to a synchronous function that parses a large HTML page. What is happening, and what are two ways to fix it?
Show answer
The synchronous parse runs on the event loop's single thread, and a coroutine only yields control at an await, so every other task waits until the parse finishes. One fix is to move the parse off the loop with asyncio.tothread, which helps if the parser releases the GIL. If it is pure Python, the thread still competes for the GIL, but the loop thread gets scheduled in between and stalls are shorter. The stronger fix is to send the parse to a ProcessPoolExecutor with loop.runin_executor, so it runs on another core with its own GIL. In both cases, measure the freeze duration before and after.