Collect Thread Pool Results and Errors
Core idea
ThreadPoolExecutor manages a bounded number of worker threads. submit returns a concurrent.futures.Future; result waits for completion and returns the value or raises the worker exception. map yields results in input order; as_completed yields completed futures without imposing input order.
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(abs, [-3, 8, -1]))print(results)Map preserves input order regardless of completion order.
Expected output:
[3, 8, 1]Observe a worker exception
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(int, 'bad') try: future.result() except ValueError: print('invalid input')print(future.done())The exception is delivered through result. A failed future is still done.
Expected output:
invalid inputTrueCommon mistake
Future.cancel cannot stop an already running callable. A worker waiting for another future in the same saturated pool can deadlock. Observe failures and use cooperative stop signals.
Practice
Submit two conversions, one invalid; collect each result separately and retain successful values without hiding errors.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Thread pools and futures
Check your understanding of thread pools and futures.
What is printed?
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(1) as p: print(p.submit(pow, 2, 3).result())What is printed?
from concurrent.futures import Futuref=Future(); f.set_result(7)print(f.done(), f.result())What happens when result observes a failed future?
Which operation preserves input order?