Futures as they complete in Python
Reacting to results in finish order, not submit order.
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def job(name, seconds):
time.sleep(seconds)
return name
with ThreadPoolExecutor() as pool:
futures = {pool.submit(job, f"task-{i}", i / 10): i
for i in range(3, 0, -1)}
order = []
for future in as_completed(futures):
order.append(future.result()) # fastest lands first
How it works
submitschedules each job and returns a future.as_completedyields futures the moment they finish.- The fastest task lands first regardless of order.
Keywords and builtins used here
asdefforjobrangereturnwith
The run, in numbers
- Lines
- 15
- Characters to type
- 349
- Tokens
- 92
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 50 seconds.
Step 4 of 4 in Threads & processes, step 31 of 53 in Pythonic Python.