`concurrent.futures`
concurrent.futures is a high-level interface for running callables in a pool of threads or processes. You submit work, get back a Future, and collect results as they finish.
Detailed Explanation
The module has two executors. ThreadPoolExecutor runs functions in threads. ProcessPoolExecutor runs them in processes. Both implement submit(fn, *args), map(fn, iterable), shutdown, and the context-manager protocol. submit returns a Future with result(), exception(), done(), add_done_callback, and cancel (which only works if the task has not started).
as_completed(futures) yields futures as they finish, not in submission order. wait blocks until a set is done. map yields results in input order and can hide which call failed until you iterate to that item.
Pick the executor the same way you pick threads vs processes. I/O-bound: threads. CPU-bound Python: processes. max_workers defaults to a small multiple of CPU count for threads (I/O) and to the CPU count for processes. Too many process workers thrash. Too many thread workers spend time switching.
Exceptions in a worker are stored on the future. future.result() re-raises them in the caller. If you ignore the future, you ignore the error. Always collect results or attach a callback that logs exceptions.
ProcessPoolExecutor has the same pickling and __main__ rules as multiprocessing. The function and its arguments must pickle. The entry script must be import-safe.
This API does not replace asyncio. loop.run_in_executor is the bridge: it schedules a blocking callable on a thread or process pool without blocking the event loop. Use that when an async app must call a blocking library.
Code Examples
from concurrent.futures import ThreadPoolExecutor, as_completed
def lookup(sku: str) -> str:
return sku.lower()
with ThreadPoolExecutor(max_workers=4) as pool:
futures = {pool.submit(lookup, s): s for s in ["A-1", "B-2"]}
for fut in as_completed(futures):
print(futures[fut], fut.result())from concurrent.futures import ProcessPoolExecutor
def fib(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
if __name__ == "__main__":
with ProcessPoolExecutor() as pool:
print(list(pool.map(fib, [10, 20]))) # [55, 6765]Common Gotchas
Dropping a future
exceptions vanish. Call `result()` or `add_done_callback`.
Passing a lambda to `ProcessPoolExecutor`
pickling fails. Use a module-level function.
`map` delays errors until iteration
a crash in item 0 is silent if you never iterate.
`cancel` cannot stop a running thread
it only drops work that has not started. Use a stop event inside the callable.