Sub topic 8
Thread and process pools with concurrent.futures
This chapter assumes you can start threads and processes by hand, that you know the GIL limits CPU-bound threads, and that you know processes need picklable arguments. If any of that is shaky, review the earlier chapters on threads, the GIL, and processes first.
Why use a pool
Creating a Thread or Process for every task has costs. Starting a process is expensive. Thousands of threads waste memory. You also have to collect results yourself, usually through a shared list or a queue, and carry exceptions across by hand.
The concurrent.futures module wraps this in one interface. An executor owns a fixed set of workers. You hand it callables, and it returns a Future for each one. A future is a placeholder for a result that may not exist yet.
There are two executors with the same API:
ThreadPoolExecutorruns tasks in threads of the current process.ProcessPoolExecutorruns tasks in separate worker processes.
Because the API is shared, you can often switch between them by changing one class name. That makes it easy to measure which one suits your workload.
Submitting work
The executor has two main ways to submit work: submit and map.
submit(fn, *args, **kwargs) schedules one call and returns a Future immediately. map(fn, *iterables) schedules one call per item and returns an iterator of results in input order.
Use the executor as a context manager. Leaving the with block calls shutdown(wait=True), which waits for all pending work and then releases the workers.
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 [0, 2, 4, 6, 8] in about one second. Each thread releases the GIL while it sleeps, so the five waits overlap.
Worker counts
If you omit max_workers, the defaults differ by executor:
| Executor | Default `max_workers` | Reason |
|---|---|---|
| `ThreadPoolExecutor` | `min(32, cpu_count + 4)` | Threads mostly wait, so more than the core count is useful |
| `ProcessPoolExecutor` | Number of available CPUs | More CPU-bound workers than cores gain nothing |
For I/O-bound work against a remote service, the right number is often set by what the service tolerates, not by your CPU count. Set it explicitly in that case.
Working with futures
A Future has a small set of methods you will use often:
result(timeout=None)blocks until the call finishes. It returns the value or re-raises the exception the task raised.exception(timeout=None)returns the exception instead of raising it, orNoneif the task succeeded.done(),running(), andcancelled()report the current state without blocking.cancel()succeeds only if the task has not started. It returnsFalsefor a running or finished task.add_done_callback(fn)callsfn(future)when the future finishes.
Callbacks do not necessarily run on the main thread. They run in a thread of your process, so keep them short and thread-safe.
Handling results as they finish
map returns results in input order, so one slow item delays everything after it. When you want to handle each result as soon as it is ready, use as_completed. It takes a collection of futures and yields each one when it finishes.
A dictionary from future to input is a common way to remember which task produced which result.
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fake_download(n):
time.sleep(1 if n != 0 else 2)
if n == 3:
raise ValueError(f"bad item {n}")
return n * 2
with ThreadPoolExecutor(max_workers=5) as pool:
futures = {pool.submit(fake_download, 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)Item 0 takes two seconds, so it prints last even though it was submitted first. Item 3 prints its failure when result() re-raises the ValueError.
For coarser control, wait(futures, timeout=None, return_when=ALL_COMPLETED) returns two sets, done and not_done. The other return_when values are FIRST_COMPLETED and FIRST_EXCEPTION.
How errors travel
An exception raised inside a task does not crash the pool. The executor stores it on the future. It surfaces when you call result() or exception().
map behaves differently, and this catches many people. The exception is raised from the iterator at the position of the failed item. After that, you cannot resume the iterator.
from concurrent.futures import ThreadPoolExecutor
def check(n):
if n == 2:
raise ValueError("two")
return n
with ThreadPoolExecutor(max_workers=2) as pool:
try:
for value in pool.map(check, range(4)):
print(value)
except ValueError as exc:
print("caught", exc)This prints 0, 1, then caught two. Item 3 may still have run, but you never see its result. If you need every outcome, including the failures, use submit with as_completed and catch exceptions per future.
With a process pool, the exception is pickled in the worker and re-raised in the parent. The original traceback is attached as the __cause__ of the re-raised exception, so you can still see where it failed.
Timeouts and cancellation
Passing timeout to result() limits how long you wait, not how long the task runs. If it expires, you get concurrent.futures.TimeoutError (the same class as the built-in TimeoutError since Python 3.11). The task keeps running.
> There is no safe way to kill a running thread, and the pool does not try. If a task can hang, give it its own timeout inside the task, for example a socket or HTTP timeout.
To drop queued work on exit, call shutdown(wait=True, cancel_futures=True) (Python 3.9+). It cancels every task that has not started and waits only for the ones already running.
Process pools: what changes
ProcessPoolExecutor has the same interface, but the work crosses a process boundary. Three consequences follow.
- Arguments, return values, and the function must be picklable. Module-level functions work. Lambdas, nested functions, and objects holding open sockets or locks do not.
- Each call has overhead. Pickling and sending data costs time, so tiny tasks can run slower than a plain loop.
- The
__main__guard is required under thespawnstart method, which is the default on Windows and macOS, because each worker re-imports your module.
Use chunksize with map on a process pool to batch many small items into one message. The thread pool ignores this argument.
from concurrent.futures import ProcessPoolExecutor
def square(n):
return n * n
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
results = list(pool.map(square, range(1000), chunksize=50))
print(sum(results)) # 332833500Here the 1000 items travel in 20 batches instead of 1000 separate messages.
Useful constructor options
initializerandinitargsrun a function once in each worker at startup. Use them to load a model or open a connection once per worker, not once per task. Both executors support them.max_tasks_per_child(processes only, Python 3.11+) replaces a worker after it has run that many tasks. It limits slow memory growth from a leaky library.mp_contextlets you pick a start method, such asmultiprocessing.get_context("spawn"), instead of the platform default.
Failure modes
Broken process pool
If a worker dies abruptly, for example through an out-of-memory kill or a crash in a C extension, the pool cannot trust its state. Pending and future calls raise concurrent.futures.process.BrokenProcessPool. You must create a new executor. Thread pools do not have this problem, because a bad thread takes the whole process down with it.
Deadlock from nested submission
A task that submits more work to the same pool and then waits for it can deadlock. If every worker is occupied by a waiting parent task, no worker is free to run the children. Avoid waiting on futures from inside the pool that runs them. Use a separate pool for the inner level, or restructure so the parent collects results.
Non-obvious sharing
Thread-pool tasks share memory, so the race conditions and locks from earlier chapters still apply. Process-pool tasks get copies, so mutating a global in a worker does not change the parent's value. Return results instead.
Picking an executor
Use these checks in order:
- If the work waits on network, disk, or a subprocess, start with
ThreadPoolExecutor. - If the work is pure-Python computation on a standard GIL build, use
ProcessPoolExecutor, and make tasks large enough to repay the pickling cost. - If a native library releases the GIL, such as many numeric or compression routines, threads may work and are cheaper. Measure to confirm.
- Time both with realistic input. A one-line change of the executor class makes the comparison cheap.
Exercise
You call pool.map(parse, files) on a ProcessPoolExecutor with 10,000 small files, and it runs slower than a plain for loop. Name two changes that may help, and one thing you must check about parse.
Show answer
Pass a larger chunksize (for example 100) so items are sent in batches, and make each task do more work, such as parsing a whole group of files per call, to amortize pickling and dispatch cost. Check that parse is a module-level function whose arguments and return values are picklable. Also check that the script has an if __name__ == "__main__": guard if the platform uses spawn.
Exercise
You submit five tasks to a ThreadPoolExecutor and one raises an exception. You never call result() on that future. Does your program crash, and how could you have found out about the failure?
Show answer
The program does not crash and the exception is not printed. The executor stores it on the future. You find it by calling fut.result() (which re-raises it) or fut.exception(), for example while looping over as_completed.