Concurrency: threads, processes and async¶
What you'll be able to do¶
- Choose threads, processes, or
asynciofrom the kind of work your program does. - Put a limit on concurrent work so a fast producer cannot overwhelm a slower service.
- Spot a race on shared data and test a fix without relying on lucky timing.
Many tasks, two meanings of “at once”¶
Concurrency means structuring a program to make progress on several tasks during the same period. Parallelism means two tasks actually run at the same instant, such as on separate CPU cores. A single worker can switch tasks whenever one waits; parallel work needs more execution capacity.
An API call is usually I/O-bound: much of its time is spent waiting for a network response. Tokenizing text in pure Python is CPU-bound: the CPU spends the time doing work. Ask where the time goes before adding workers. More local cores will not make one remote request faster; overlapping waits will not speed up Python computation.
What blocking costs¶
A blocking call stops its thread until a result arrives. During a network wait, that thread does no useful Python work. Consider ten independent API calls that each take 200 ms. Sequentially, idealized elapsed time is 10 × 200 ms = 2,000 ms, or about 2 seconds. If all waits overlap, it approaches 200 ms, or about 0.2 seconds. Setup, scheduling, variable latency, and service limits add time.
Threads overlap waits because the operating system can run another thread while one blocks. asyncio overlaps waits when a coroutine yields at await, letting one event-loop thread work on another task. Neither guarantees the remote API can handle ten calls at once. The gain is in completing the batch sooner.
Choose a Python tool from the bottleneck¶
For blocking I/O, start with a bounded concurrent.futures.ThreadPoolExecutor. Its map returns results in input order even if calls finish in another order. A pool limits workers, and iterating the results re-raises a worker's exception. The with block shuts it down. max_workers does not bound queued submissions: by default, map reads and submits the whole input up front. For large or streaming inputs, feed workers through a bounded queue or submit in bounded batches.
from concurrent.futures import ThreadPoolExecutor
def fetch(item): # Replace with a blocking API call.
return item.upper()
with ThreadPoolExecutor(max_workers=4) as pool:
answers = list(pool.map(fetch, ["a", "b", "c"]))
assert answers == ["A", "B", "C"]
Threads share memory and can see the same objects. In a standard GIL-enabled Python build, the global interpreter lock (GIL) lets only one thread execute Python bytecode at a time. Threads help during I/O waits, but generally do not speed up CPU-bound pure-Python loops. Some numerical libraries release the GIL during native code, so measure those workloads.
For CPU-bound pure-Python work, use concurrent.futures.ProcessPoolExecutor or multiprocessing. Separate processes can execute on separate cores, but have separate memory: inputs and results often need to be pickled and copied. Sending a huge array for every tiny job may cost more than the work saves. Consider shared memory only when measurements justify it. Python is moving toward optional free-threaded builds; check the Python documentation for your version and build.
Async code yields instead of blocking¶
An asyncio event loop drives tasks that cooperate by reaching await. async def defines a coroutine; calling it creates a coroutine object, while await actually runs it. asyncio.gather waits for several awaitables and returns results in argument order. By default, the first exception reaches the caller at once, while the other awaitables are not cancelled. Creating tasks lets work proceed while the caller does something else; keep references to tasks and await their completion or handle their failures.
import asyncio
async def work(i, gate):
async with gate:
await asyncio.sleep(0) # Yield; real code awaits async I/O.
return i * 2
async def main():
gate = asyncio.Semaphore(3)
return await asyncio.gather(*(work(i, gate) for i in range(5)))
assert asyncio.run(main()) == [0, 2, 4, 6, 8]
The semaphore allows at most three calls inside the protected section. It limits work in flight, not the number of coroutine objects created. For a large input, feed fixed workers from a bounded queue instead of creating 100,000 tasks at once. asyncio.wait_for(coro, seconds) gives an operation a timeout: after seconds, it requests cancellation and waits for that to finish. It is not a hard wall-clock limit, because cleanup can take longer. Code that catches cancellation must clean up and re-raise it. Callers can also cancel tasks explicitly.
Calling blocking code such as time.sleep() or a synchronous network client inside async def blocks the whole event-loop thread. Use an async client, or move blocking code to a thread with asyncio.to_thread or the loop's run_in_executor. A coroutine is not automatically nonblocking merely because it is spelled async def.
Shared state creates races¶
Suppose two threads both run counter += 1. Each must read a value, compute a new one, and write it back. If both read 7 before either writes, both can write 8: one increment is lost. This read-modify-write race can occur even when individual operations look small. The GIL is not a substitute for a rule that protects shared state, and code that works under one interpreter configuration may fail under another.
Use a threading.Lock around the whole read-modify-write operation. Hold it briefly and release it in a with block. Two locks can deadlock if one thread holds A and waits for B while another holds B and waits for A. If you need both, acquire them in the same order everywhere. Better still, reduce shared mutable state: pass immutable values, give each worker its own data, or send jobs and results through queue.Queue. A bounded queue also makes a fast producer wait when consumers fall behind; a sentinel value can tell each worker to exit after the jobs are done.
Put limits where work accumulates¶
Unbounded concurrency turns a queue in your program into a flood at the callee. Ten calls might be fine; 10,000 simultaneous calls can exhaust connection pools, memory, provider quotas, or database capacity and trigger rate limits. Choose a worker cap from connection capacity and observed latency, then measure throughput, errors, and queue depth. More threads are not always faster.
A concurrency cap is not a rate limit. Ten workers making 100 ms calls can start about 10 / 0.1 = 100 calls per second, even if your quota is 10 per second, so enforce requests per second with a separate rate limiter. A semaphore caps active operations; a bounded queue caps waiting jobs. A streaming pipeline may need both.
Treat retries as more work: if every failed call retries immediately, overload can grow. Pair a concurrency cap with a timeout, a retry budget, and rate-limit handling. The rate-limiting and timeouts and retries lessons develop those controls.
Concurrent bugs are often flaky because scheduling changes each run. Test behavior: assert every item is processed once, promised order is preserved, exceptions reach the caller, and peak in-flight work stays below the cap. Use barriers or events to force a race. Avoid time.sleep() in tests; machine speed changes what it proves. Log task IDs, queue depth, and exceptions when diagnosing failures.
For AI engineers¶
For AI engineers
A script that sends 10,000 prompts to an LLM API is I/O-bound while it waits for responses. Use bounded async or thread concurrency, then add timeouts, rate-limit handling, and limited retries. A single unlimited gather can create too much local work and overwhelm the provider. A data preprocessing pipeline is a producer/consumer system: a bounded queue stops readers from outrunning tokenizers or writers. Data-loader workers are commonly processes because they can run CPU work in parallel; passing large arrays between them has a copy cost, so batch and measure. GPU launches may be asynchronous relative to the CPU: a Python timer around a launch may measure submission rather than completed GPU work, so synchronize when measuring completion.
Common mistakes¶
- Using threads for CPU-bound pure Python: the usual GIL prevents bytecode from running in parallel. Try processes and measure serialization cost.
- Launching every coroutine at once: a semaphore caps active calls, but a huge
gatherstill allocates tasks. Use a bounded queue and fixed workers for large streams. - Blocking inside
async def: a synchronous client ortime.sleepstalls unrelated tasks on the event loop. Use async I/O or a thread bridge. - Sharing an unsafe client or counter: inspect a client's thread-safety contract; protect mutable state or give each worker its own instance.
- Losing worker errors or cleanup: await futures and tasks, observe exceptions, and close pools and clients with context managers or
finally. - Using sleeps to test races: force the interleaving with barriers or events, then assert the result.
Check yourself¶
Ten independent API calls each wait 200 ms. What is the idealized batch time sequentially and with full overlap?
Sequentially, 10 × 200 ms = 2 seconds. With all waits overlapped, about 200 ms. Real overhead and service limits make the concurrent run longer.
A pure-Python tokenizer uses one CPU core at full load. Should you start with a thread pool or process pool, and what cost must you check?
Start with a process pool for possible parallel execution across cores. Measure the cost of pickling and copying inputs and results, especially large arrays.
An async def handler calls a synchronous API client and other requests freeze. What caused it?
The blocking client occupied the event-loop thread. Use an async client or move the blocking call to a thread with to_thread or run_in_executor.
Two threads increment a shared value but the final count is low. What test and fix would you use?
To reproduce it, start the workers together and, in the unsafe version only, put a barrier between the read and the write so both read the old value. Fix it with a lock around the entire read-modify-write, or avoid shared mutable state, then assert the exact final count. A barrier left inside the lock would deadlock: the holder waits for a thread that cannot get the lock.
Lab¶
Build five small concurrency helpers in code/concurrency/. Map jobs through a thread pool and add an async timeout fallback. Fix a lost-update counter that the tests race on purpose, then bound an async gather while preserving input order. Build a bounded producer/consumer queue with sentinel shutdown. Tests force overlap with events instead of asserting how fast your code runs. Run: cd code/concurrency && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Reference: Python documentation
- Your handbook: Software Engineering Handbook, ch. 2 "OS & Concurrency"