Concurrency: threading, multiprocessing & asyncio
Choosing and using threading, multiprocessing and asyncio correctly.
Threading for I/O-bound work
Threads overlap waiting time for I/O-bound tasks; the GIL means they don't speed up pure computation.
threading.Thread(target=func, args=(...)).start() runs func concurrently with the rest of the program; concurrent.futures.ThreadPoolExecutor offers a higher-level way to run many such calls and collect their results via .map() or .submit(). In the default GIL-enabled CPython build, only one thread executes Python bytecode at a time, so pure-Python threads only provide real speedup for I/O-bound work — network requests, file access — where the GIL is released while waiting. That is not the whole picture for a Python 3.14 curriculum, though: native extension code can release the GIL even on the default build, so some CPU-heavy library calls already parallelize with threads, and Python 3.14's officially supported free-threaded build removes the GIL entirely, letting pure-Python CPU-bound threads run in parallel too — a topic covered later in this path. Shared mutable state accessed from multiple threads needs a threading.Lock to avoid race conditions on compound operations, regardless of which build is running.
Key points
- On the default GIL-enabled CPython build, threads mainly speed up I/O-bound work; free-threaded 3.14 and GIL-releasing native code are exceptions covered later
- ThreadPoolExecutor.map()/.submit() is the higher-level way to run many concurrent calls
- Shared mutable state across threads needs a Lock to avoid race conditions
Code
from concurrent.futures import ThreadPoolExecutor
import requests
urls = ["https://example.com"] * 5
with ThreadPoolExecutor(max_workers=5) as pool:
responses = list(pool.map(requests.get, urls))
print([r.status_code for r in responses])Fetching five URLs concurrently with a thread pool, overlapping their network wait time.
Common pitfalls
- Using threads for a CPU-bound loop (like heavy math) gives no real speedup because of the GIL
- Incrementing a shared counter from multiple threads without a Lock can silently lose updates
Practice exercise
Write a script that downloads 10 URLs sequentially, time it, then rewrite it using ThreadPoolExecutor and compare the time difference.
Multiprocessing for CPU-bound work
Separate processes each get their own interpreter and GIL, giving true parallelism for heavy computation.
concurrent.futures.ProcessPoolExecutor runs work across multiple separate operating-system processes, each with its own Python interpreter and runtime state, so CPU-bound work genuinely runs in parallel across cores — unlike plain threading on the default build. On the standard CPython build, each of those processes also carries its own independent GIL, so they never contend with each other the way threads sharing one process would; a process could instead be running Python 3.14's free-threaded build, where there is no GIL at all to begin with, but the cross-process isolation is what actually delivers the parallelism either way. The trade-off: since each process has separate memory, arguments, and return values must be pickled to cross the process boundary, so they cannot be a lambda or contain unpicklable objects like open file handles, and process startup has real overhead, making this approach worthwhile mainly for substantial, genuinely CPU-heavy chunks of work rather than many tiny tasks.
Key points
- Each process gets its own interpreter and runtime state; on the default build that also means its own independent GIL
- Arguments and return values must be picklable to cross the process boundary
- Process startup has real overhead — best for substantial, genuinely CPU-heavy work
Code
from concurrent.futures import ProcessPoolExecutor
def is_prime(n):
return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1))
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
results = list(pool.map(is_prime, range(2, 100000)))
print(sum(results), "primes found")Checking primality across a large range in parallel across CPU cores using a process pool.
Common pitfalls
- pool.map(lambda n: n * 2, data) raises a pickling error — use a module-level function instead of a lambda
- Multiprocessing code on Windows must be guarded by if __name__ == "__main__": or it re-imports and re-runs unexpectedly
Practice exercise
Write a CPU-heavy function (like computing the sum of squares up to a large n for many different n values) and compare its total runtime with a plain loop versus ProcessPoolExecutor.map().
asyncio and async/await
Cooperative concurrency on a single thread: coroutines take turns at await points instead of running in parallel.
async def defines a coroutine function; calling it does not run its body, it returns a coroutine object that must be awaited or scheduled to actually run. Inside a coroutine, await waits on an awaitable and may suspend the current coroutine — most commonly at an I/O wait point — letting the event loop run other ready coroutines in the meantime, then resumes once the awaited operation completes; this is cooperative multitasking on a single thread, not true parallelism. asyncio.gather(*coroutines) runs several coroutines concurrently and collects their results in order, and stays genuinely useful for that ordered-aggregation case, but asyncio.TaskGroup is now the preferred structured-concurrency tool for a related group of tasks where lifecycle and failure handling matter, since it cancels the remaining sibling tasks when one of them fails.
Key points
- async def creates a coroutine function; calling it just returns an object, it doesn't run yet
- await waits on an awaitable and may suspend — typically at I/O — letting other coroutines run; cooperative, not parallel
- gather() gives ordered aggregation; TaskGroup is now preferred when task lifecycle/failure handling matters
Code
Run the code to see the result.
Three coroutines that each "wait" one second, but run concurrently and finish in about one second total.
Common pitfalls
- Calling an async function without await (or asyncio.run/gather) just creates a coroutine object and does nothing
- A coroutine that does real CPU work without ever awaiting blocks the entire event loop for every other coroutine
Practice exercise
Rewrite the sequential URL-download exercise from the threading lesson using asyncio and an async HTTP client, and compare its behavior conceptually to the thread-pool version.
Choosing between threading, multiprocessing and asyncio
A decision guide: classify the workload first, then pick the concurrency model that actually fits it.
Start by classifying the workload: is it I/O-bound (spends most of its time waiting on the network, disk or another process) or CPU-bound (spends most of its time actually computing)? For I/O-bound work with many concurrent operations and a codebase that can adopt async/await throughout, asyncio typically scales best; for I/O-bound work in a codebase using blocking libraries that were never written for asyncio, threading (or a ThreadPoolExecutor) is the pragmatic choice. CPU-bound work needs more care in a Python 3.14 curriculum: on the default GIL-enabled CPython build, multiprocessing (or ProcessPoolExecutor) remains the mature, broadly compatible default, since the GIL there prevents pure-Python threads from running bytecode in parallel — but it is no longer the only option. Python 3.14 also added InterpreterPoolExecutor, where each worker runs in its own isolated interpreter within one process for true multi-core parallelism at lower overhead than separate processes; the officially supported free-threaded build lets ordinary Python threads run CPU-bound code in parallel directly; and native extensions like NumPy already release the GIL for their own CPU-heavy work even on the default build. Which of these actually fits best still depends on data-sharing needs, serialization cost, startup overhead and library compatibility, not the I/O-versus-CPU split alone.
Key points
- Classify first: I/O-bound (waiting) versus CPU-bound (computing)
- I/O-bound + async-friendly codebase favors asyncio; I/O-bound + blocking libraries favors threading
- CPU-bound: multiprocessing is the mature default on the standard GIL build, but InterpreterPoolExecutor, free-threaded Python, and GIL-releasing native code are now real alternatives
Code
# Rule of thumb, not code to run:
# Many small waits, async-ready libraries -> asyncio
# Many small waits, blocking libraries -> threading / ThreadPoolExecutor
# Heavy computation, default GIL build -> multiprocessing / ProcessPoolExecutor
# Heavy computation, want in-process isolation -> InterpreterPoolExecutor (3.14+)
# Heavy computation, free-threaded build available -> plain threads can parallelize tooA quick decision rule of thumb for picking a concurrency model based on the workload's shape and the interpreter build in use.
Common pitfalls
- Reaching for multiprocessing on I/O-bound work adds process overhead for no real benefit over threading or asyncio
- Reaching for plain threading on genuinely CPU-bound work delivers no parallel speedup on the default GIL build — free-threaded Python and GIL-releasing native code are the exceptions worth knowing about
Practice exercise
For each of these three tasks, decide and justify in one or two sentences which concurrency model fits best, and name at least one alternative worth considering: (1) resizing 10,000 images, (2) calling 500 independent REST APIs, (3) a chat server handling thousands of open connections.