Phase 12 of 25 · Topic 12.5

concurrent.futures: ProcessPoolExecutor & ThreadPoolExecutor

1Concept

`concurrent.futures` provides a high-level, unified interface for asynchronous task execution using pool workers. Submitting callables returns `Future` objects representing deferred results.

2Architecture Diagram

Pool Executor (4 Workers)
  ├── Task 1 -> Worker 0
  ├── Task 2 -> Worker 1
  └── Returns Future objects ---> future.result() retrieves value when ready

3Code Example

Python 3.12
from concurrent.futures import ThreadPoolExecutor

def fetch_metric(metric_id: str) -> str:
    return f"Metric-{metric_id}: OK"

with ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(fetch_metric, f"SYS_{i}") for i in range(3)]
    for f in futures:
        print(f"Completed: {f.result()}")

4Expected Output

Completed: Metric-SYS_0: OK
Completed: Metric-SYS_1: OK
Completed: Metric-SYS_2: OK

5Key Takeaways

  • `executor.map(func, iterable)` preserves output order corresponding to inputs.
  • `future.result(timeout=5)` blocks until the task completes or times out.
  • `as_completed(futures)` yields futures as soon as each individual worker finishes.