Sub topic 8
Thread and process pools with concurrent.futures
This chapter assumes you know how to start a threading.Thread, what the GIL limits, and the difference between I/O-bound and CPU-bound work. It also assumes you are comfortable with with statements.
One interface, two kinds of workers
Creating threads or processes by hand means managing start, join, and result passing yourself. The concurrent.futures module wraps this in a pool. A pool keeps a fixed set of workers alive and feeds them tasks.
ThreadPoolExecutor and ProcessPoolExecutor share one interface, so changing the worker type is usually a one-word edit.
map: the simplest case
pool.map(func, iterable) works like the built-in map, but runs calls on the workers. Results come back in input order, even if later tasks finish first.
import time
from concurrent.futures import ThreadPoolExecutor
def fake_download(n):
time.sleep(1) # stands in for waiting on the network
return n * 2
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(fake_download, range(5)))
print(results, f"{time.perf_counter() - start:.1f}s")This prints in about one second, not five, because sleeping threads release the GIL. Leaving the with block calls shutdown(wait=True), which waits for all pending work.
submit and futures
pool.submit(func, *args) returns a Future immediately. A future is a handle to a result that may not exist yet. Call future.result() to wait for it. If the task raised an exception, result() raises it again in your code.
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(n):
if n == 3:
raise ValueError(f"bad input {n}")
return n * 2
with ThreadPoolExecutor(max_workers=4) as pool:
futures = {pool.submit(fetch, n): n for n in range(5)}
for fut in as_completed(futures):
n = futures[fut]
try:
print(n, fut.result())
except ValueError as exc:
print(n, "failed:", exc)as_completed yields futures in completion order, which suits progress reporting. The dictionary maps each future back to its input. With map, an exception appears only when you reach that item while iterating the results.
Switching to processes
For CPU-bound pure-Python work, change the class. The workers are separate processes, each with its own GIL.
from concurrent.futures import ProcessPoolExecutor
def count_down(n):
while n > 0:
n -= 1
return n
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=4) as pool:
print(list(pool.map(count_down, [10_000_000] * 4)))Process pools add three requirements that thread pools do not have:
- The function and its arguments are pickled to reach a worker, and the result is pickled on the way back. The function must be defined at module top level, so lambdas and nested functions fail.
- Under the
spawnstart method, each worker re-imports your main module, so theif __name__ == "__main__":guard is required. - Every task pays for pickling and transfer. Tiny tasks can run slower than serial code.
Comparing the two pools
| Aspect | ThreadPoolExecutor | ProcessPoolExecutor |
|---|---|---|
| Best for | I/O-bound work | CPU-bound pure-Python work |
| Memory | Shared | Separate per worker |
| Data passing | Direct references | Pickled copies |
| Startup cost | Low | Higher |
| `__main__` guard | Not needed | Needed under spawn |
Common mistakes
- Setting
max_workerswithout thinking. The defaults depend on the CPU count, and the right value for I/O work is often higher than for CPU work. - Forgetting that a task's exception stays hidden until you call
result(), or iteratemap. A submitted task that fails and is never checked fails silently. - Mutating shared state from threaded tasks without a lock. Pools do not make shared data safe.
- Submitting unpicklable objects, such as open files or locks, to a process pool.
Exercise
You submit 20 tasks to a ProcessPoolExecutor and the program fails with a pickling error mentioning a lambda. What is the cause, and what is the fix?
Show answer
Process pools pickle the function so it can reach a worker, and lambdas cannot be pickled by reference. Replace the lambda with a named function defined at module top level (use functools.partial if you need to bind arguments).