Part 13 / Topic 6 of 11
concurrent.futures
concurrent.futures gives you one simple API for both threads and processes. You create a pool (a group of ready workers), hand it work, and get results back.
Like a call-centre manager: you hand tasks to the team and get a receipt for each one.
| Tool | Meaning |
|---|---|
ThreadPoolExecutor(max_workers=4) |
A pool of 4 threads |
ProcessPoolExecutor(max_workers=4) |
A pool of 4 processes (needs the __main__ guard) |
pool.submit(func, arg) |
Start one call, get a Future: a "receipt" for a result that comes later |
future.result() |
Wait for the result (re-raises any error from the worker) |
pool.map(func, items) |
Run func on each item; results in the same order as items |
as_completed(futures) |
Gives futures back in the order they finish |
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_price(item: str, seconds: float) -> str:
time.sleep(seconds) # pretend to call a price API
return f"{item} done"
with ThreadPoolExecutor(max_workers=3) as pool: # 'with' waits for all
futures = [
pool.submit(fetch_price, "rice", 0.3),
pool.submit(fetch_price, "dal", 0.1),
pool.submit(fetch_price, "ghee", 0.2),
]
for future in as_completed(futures): # fastest first
print(future.result())
print(list(pool.map(str.upper, ["a", "b"]))) # input order
# dal done
# ghee done
# rice done
# ['A', 'B']
Choosing between them
| Your work | Use | Why |
|---|---|---|
A few to a few hundred blocking I/O calls (urllib, files, database) |
ThreadPoolExecutor |
Simple, and threads are fine while waiting |
| Heavy calculations | ProcessPoolExecutor |
Many cores, each process has its own GIL |
Thousands of network calls, or your code is already async |
asyncio (the asyncio topics that follow) |
Tasks are much lighter than threads |
| One quick task | Nothing! Plain code | Pools add overhead and complexity |
| Free-threaded Python (3.14t) and CPU work | ThreadPoolExecutor can work |
No GIL, but check your packages support it |
Full program: examples/05_futures.py (as_completed vs map, an error inside a worker, and ProcessPoolExecutor counting primes).
๐ Going deeper: with no
max_workers,ThreadPoolExecutorusesmin(32, cores + 4)threads andProcessPoolExecutoruses one process per core.
Read more: the official concurrent.futures documentation.
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.