Sub topic 3
Choosing Between Threads, Processes, and asyncio
This chapter assumes you can write Python functions, use standard-library context managers, and recognize I/O-bound work as waiting on files, networks, or other external systems.
Select the concurrency model
Choose the model from the workload:
| Workload | Usually suitable | Reason |
|---|---|---|
| Many blocking network requests | Threads or `asyncio` | Most time is spent waiting |
| Pure-Python CPU calculations | Processes | Separate processes can use separate CPU cores |
| CPU work inside native libraries | Threads or processes | Some libraries release the GIL |
Threads are often the simplest choice for existing blocking code. asyncio uses cooperative concurrency: one thread runs an event loop, and tasks yield control when they await. It works well when the libraries you call support asynchronous operations. Processes provide stronger isolation, but starting them and moving data between them costs more.
Process startup and communication
Use the __main__ guard whenever code creates processes. The spawn method starts a fresh interpreter and imports your module. fork copies the parent process and is common on some Unix systems, while forkserver starts children through a clean server process. Availability and defaults vary by operating system and Python version.
from multiprocessing import Process, Queue
def worker(output):
output.put(sum(range(1_000_000)))
if __name__ == "__main__":
queue = Queue()
process = Process(target=worker, args=(queue,))
process.start()
result = queue.get()
process.join()
print(result)A Queue is convenient for many messages. A Pipe gives a direct connection between two processes. Values sent through either mechanism are usually pickled, meaning Python converts them to bytes and reconstructs them elsewhere. Large or frequent messages can erase the speed gained from parallel execution.
Native libraries and the GIL
The Global Interpreter Lock (GIL) protects CPython's internal object state by allowing only one thread at a time to execute Python bytecode in a standard build. A native extension can release the GIL while performing its own computation, such as numerical array operations or compression. Those operations may then run in parallel threads. This depends on the library, not merely on the fact that a function is slow.
The GIL's direction
Free-threaded CPython builds can run Python bytecode without the traditional process-wide GIL, but they remain an optional compatibility and deployment choice. Some extensions may need updates, and performance can differ. Per-interpreter GIL work gives separate subinterpreters separate locks, while keeping isolation between interpreters. Neither feature removes the need to measure a real application.
Exercise
Which model is the strongest first choice for four independent, pure-Python CPU calculations?
Show answer
A process pool, because separate processes can execute the calculations on separate CPU cores without sharing one standard-build GIL.