Thread Pool Futures With as_completed
Submit many small jobs to a ThreadPoolExecutor and consume results as each future finishes, instead of blocking in submission order.
Code
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def work(name: str, seconds: float) -> str:
time.sleep(seconds)
return f'{name} took {seconds:.2f}s'
jobs = [('alpha', 0.05), ('beta', 0.01), ('gamma', 0.03)]
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(work, name, secs) for name, secs in jobs]
# as_completed:谁先完成谁先返回,慢任务不再挡住快任务
for future in as_completed(futures):
print('finished:', future.result())What the code does
Thread Pool Futures With as_completed comes down to the function work.
Repetition is confined to for future in as_completed(futures) — the rest of the file is straight-line. The import line is the dependency contract: ThreadPoolExecutor, as_completed come from concurrent and nothing else.
What to watch for
concurrentmust be installed first — the snippet imports it directly.
Applying it
The main signature reads def work(name: str, seconds: float) -> str
Look for the finished: prefixes when the file runs; they tie each line to its step.
The surface worth importing is work; the helpers around it are private to the snippet.
Statements that matter
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(work, name, secs) for name, secs in jobs]
# as_completed:谁先完成谁先返回,慢任务不再挡住快任务
for future in as_completed(futures):
print('finished:', future.result())
def work(name: str, seconds: float) -> str:
time.sleep(seconds)
return f'{name} took {seconds:.2f}s'
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `concurrent`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.