typestar

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

  1. submit schedules each job and returns a future.
  2. as_completed yields futures the moment they finish.
  3. The fastest task lands first regardless of order.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Threads & processes, step 31 of 53 in Pythonic Python.

← Previous Next →