On this page
concurrent
Prev: compression | Up: stdlib_module | Next: configparser
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — concurrent
Tags: #public #python3 #stdlib
Import
import concurrent
Overview
Namespace package hosting concurrent.futures (ThreadPoolExecutor, ProcessPoolExecutor, Future, as_completed, wait). Reach for concurrent.futures as the cleanest high-level interface for parallel I/O (ThreadPoolExecutor) or CPU-bound fan-out (ProcessPoolExecutor) without managing raw threading or multiprocessing primitives manually.
Quick Start
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(lambda x: x * x, [1, 2, 3, 4]))
assert results == [1, 4, 9, 16]
Implementation Walkthrough
1. Collecting Results as They Finish (submit + as_completed)
Unlike pool.map() (which waits in submission order), as_completed() yields each Future the moment it finishes so you can handle per-item errors cleanly:
from concurrent.futures import ThreadPoolExecutor, as_completed
def double_positive(n: int) -> int:
if n < 0:
raise ValueError("negative")
return n * 2
ok, errors = [], []
with ThreadPoolExecutor(max_workers=3) as pool:
futures = {pool.submit(double_positive, n): n for n in (3, -1, 5)}
for fut in as_completed(futures):
try:
ok.append(fut.result(timeout=5))
except ValueError:
errors.append(futures[fut])
assert sorted(ok) == [6, 10] and errors == [-1]
Gotchas & Boundaries
- Always pass explicit
max_workers=to cap resource usage on high-core machines. - Always use
with ...Executor(...) as pool:: Exiting thewithblock waits for all running futures to finish and cleans up threads/processes. ProcessPoolExecutorrequiresif __name__ == "__main__":on macOS/Windows and picklable top-level callables.- Don't forget to call
fut.result(): Unchecked exceptions inside submitted tasks stay silent until.result()or.exception()is inspected.
Linked from
Related notes
- tuts/python3/stdlib_module/compression Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/configparser Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getopt Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/os Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/threading Linked here; shared tags: #stdlib