Python Concurrency · Lesson 141 of 149

Python concurrent.futures

What you will learn

  • Executors: ThreadPoolExecutor and ProcessPoolExecutor
  • map and submit
  • Future objects: result, exception, done, cancel, callbacks
  • as_completed and wait
  • Timeouts and errors
  • Switching between threads and processes

1. One interface for threads and processes

Lessons 20.2 and 20.3 showed threading and multiprocessing: powerful, but with many details (queues, locks, join, pickling rules). The concurrent.futures module wraps both in one simple interface built on two ideas:

  • an executor: a pool of workers (threads or processes) that you give jobs to;
  • a future: a receipt for a job, from which you collect the result (or the error) later.
from concurrent.futures import (ProcessPoolExecutor, ThreadPoolExecutor, TimeoutError,
                                as_completed, wait, FIRST_COMPLETED)
Executor Workers are Use for
ThreadPoolExecutor threads I/O-bound work (lesson 20.2)
ProcessPoolExecutor processes CPU-bound work (lesson 20.3)

Both have the same methods, so changing from one to the other is a one-word edit. As always, use them in a with block: leaving the block waits for the jobs to finish and shuts the workers down (lesson 14.6).

2. executor.map

executor.map(function, items) works like the built-in map but runs the calls concurrently, returning the results in the order of the items:

def slow_square(x):
    time.sleep(0.3)
    return x * x


start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as ex:
    results = list(ex.map(slow_square, range(10)))
print(f"map over 10 items with 5 threads: {time.perf_counter() - start:.2f} s", results)
map over 10 items with 5 threads: 0.60 s [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Ten jobs of 0.3 s would take 3 s one by one; five workers handled them in two rounds: 0.6 s. If any call raises an exception, it is re-raised in the parent when you reach that result:

def fail_on_three(x):
    if x == 3:
        raise ValueError(f"bad value {x}")
    return x * 10


with ThreadPoolExecutor(max_workers=2) as ex:
    try:
        list(ex.map(fail_on_three, range(5)))
    except ValueError as e:
        print("map raised:", e)
map raised: bad value 3

This all-or-nothing behaviour is simple but means the remaining results are lost; submit (next section) gives finer control.

Quick check: does `executor.map` return results in the order the jobs finish?

No. It returns them in the order of the input items.

3. submit and Future

executor.submit(function, *args) starts one job and returns a Future immediately, without waiting:

with ThreadPoolExecutor(max_workers=3) as ex:
    f = ex.submit(slow_square, 7)
    print(type(f).__name__, f.done(), f.result(), f.done(), f.exception())
Future False 49 True None
Future method Meaning
f.done() has the job finished (successfully, with an error, or cancelled)?
f.result(timeout=None) wait for the result and return it; re-raises the job's exception
f.exception() wait, and return the exception (or None) instead of raising it
f.cancel() try to cancel a job that has not started yet
f.running() / f.cancelled() state queries
f.add_done_callback(fn) call fn(future) when the job finishes

Handling errors one job at a time:

with ThreadPoolExecutor(max_workers=2) as ex:
    fs = [ex.submit(fail_on_three, i) for i in range(5)]
    for i, f in enumerate(fs):
        try:
            print(i, f.result())
        except ValueError as e:
            print(i, "error:", e, "| exception():", repr(f.exception()))
0 0
1 10
2 20
3 error: bad value 3 | exception(): ValueError('bad value 3')
4 40

The other four jobs succeeded; only job 3 failed, and we saw both. That is the advantage of submit over map.

Timeouts and cancelling

with ThreadPoolExecutor(max_workers=1) as ex:
    f = ex.submit(delayed, "x", 1.0)
    try:
        f.result(timeout=0.2)
    except TimeoutError:
        print("timeout after 0.2 s; still running:", f.running())
    g = ex.submit(delayed, "queued", 0.1)
    print("cancel queued:", g.cancel(), g.cancelled())
timeout after 0.2 s; still running: True
cancel queued: True True

(delayed(name, seconds) sleeps, then returns name.) A timeout on result only stops your waiting: the job keeps running. cancel() works only for a job still waiting in the queue (here the single worker was busy with the first job, so the second was cancellable). A running job cannot be interrupted.

Callbacks

log = []
with ThreadPoolExecutor(max_workers=2) as ex:
    f = ex.submit(slow_square, 5)
    f.add_done_callback(lambda fut: log.append(fut.result()))
print("callback saw:", log)
callback saw: [25]

Callbacks run in the thread that completes the job (or immediately if it is already done), so keep them short and thread-safe (lesson 20.2).

4. as_completed and wait

To handle results as soon as each one is ready, use as_completed, which yields futures in the order they finish. A common idiom keeps a dictionary from future to a label:

with ThreadPoolExecutor(max_workers=3) as ex:
    futures = {ex.submit(delayed, name, s): name
               for name, s in [("slow", 0.6), ("fast", 0.1), ("mid", 0.3)]}
    order = [futures[f] for f in as_completed(futures)]
print("finished in order:", order)
finished in order: ['fast', 'mid', 'slow']

The jobs were submitted as slow, fast, mid, but reported as they finished. as_completed(futures, timeout=...) also accepts a timeout.

wait(futures, return_when=...) waits for a group:

with ThreadPoolExecutor(max_workers=3) as ex:
    fs = [ex.submit(delayed, n, s) for n, s in [("a", 0.5), ("b", 0.1)]]
    done, pending = wait(fs, return_when=FIRST_COMPLETED)
    print("first done:", [f.result() for f in done], "pending:", len(pending))
first done: ['b'] pending: 1

Options for return_when: FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED (the default).

5. Threads or processes: change one word

For waiting-bound jobs use threads; for computing use processes. The code is otherwise identical:

with ThreadPoolExecutor(4) as pool:
    thr = list(pool.map(heavy, jobs))

with ProcessPoolExecutor(4) as pool:
    prc = list(pool.map(heavy, jobs))

Results on the check computer for four CPU-bound jobs of the same size:

CPU work, 4 jobs: sequential 2.70 s | threads 3.07 s | processes 1.33 s
same results: True

The threads did not help, as expected (lesson 20.6), and the processes finished in about half the time. Rules for ProcessPoolExecutor are those of lesson 20.3: code under if __name__ == "__main__":, top-level functions, picklable arguments and results.

Choosing the number of workers: for threads, the number of simultaneous waits you can allow (not hundreds against one server!); for processes, about the number of cores. If max_workers is left out, Python picks a default based on the computer.

Worked example: checking sites concurrently, then CPU work in processes

Eight "sites" are checked (simulated by random-length waits, two of which fail). Four threads work through them, successes and failures are collected separately, and the results are reported as they complete. Then four heavy calculations compare sequential, thread and process execution.

import random
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed

SITES = ["alpha.example", "beta.example", "gamma.example", "delta.example",
         "epsilon.example", "zeta.example", "eta.example", "theta.example"]


def check(site):
    """Pretend to check a website: wait a while, sometimes fail."""
    rng = random.Random(site)          # same behaviour on every run
    time.sleep(rng.uniform(0.1, 0.5))
    if site.startswith(("gamma", "theta")):
        raise ConnectionError(f"{site} did not answer")
    return len(site)


def heavy(n):
    total = 0
    for i in range(n):
        total += i * i
    return total


if __name__ == "__main__":
    start = time.perf_counter()
    ok, failed = {}, {}
    with ThreadPoolExecutor(max_workers=4) as pool:
        futures = {pool.submit(check, site): site for site in SITES}
        for future in as_completed(futures):
            site = futures[future]
            try:
                ok[site] = future.result()
            except ConnectionError as error:
                failed[site] = str(error)
    elapsed = time.perf_counter() - start
    print(f"checked {len(SITES)} sites in {elapsed:.2f} s with 4 threads")
    print("ok:    ", sorted(ok))
    print("failed:", sorted(failed))
    print("one by one would take about",
          round(sum(random.Random(s).uniform(0.1, 0.5) for s in SITES), 1), "s")

    N = 12_000_000
    jobs = [N] * 4
    t = time.perf_counter(); seq = [heavy(n) for n in jobs]; t_seq = time.perf_counter() - t
    t = time.perf_counter()
    with ThreadPoolExecutor(4) as pool:
        thr = list(pool.map(heavy, jobs))
    t_thr = time.perf_counter() - t
    t = time.perf_counter()
    with ProcessPoolExecutor(4) as pool:
        prc = list(pool.map(heavy, jobs))
    t_prc = time.perf_counter() - t
    print(f"CPU work, 4 jobs: sequential {t_seq:.2f} s | threads {t_thr:.2f} s | processes {t_prc:.2f} s")
    print("same results:", seq == thr == prc)
checked 8 sites in 0.80 s with 4 threads
ok:     ['alpha.example', 'beta.example', 'delta.example', 'epsilon.example', 'eta.example', 'zeta.example']
failed: ['gamma.example', 'theta.example']
one by one would take about 2.8 s
CPU work, 4 jobs: sequential 2.70 s | threads 3.07 s | processes 1.33 s
same results: True
Part Idea
submit plus a futures dictionary each result can be matched back to its site
as_completed results handled as they arrive, not in submission order
try ... except ConnectionError around future.result() one failing site does not stop the others, and errors are collected
0.80 s vs about 2.8 s the waits overlapped on four threads
threads vs processes for CPU work threads gave no gain (3.07 s against 2.70 s), processes about halved the time

The sites are simulated; nothing was contacted. Seeding random.Random with the site name makes the pretend delays repeatable. Timings are from one computer.

Common mistakes

  • Using ThreadPoolExecutor for CPU-bound work.
  • Using map when you need individual error handling.
  • Assuming result(timeout=...) stops the job (it only stops the waiting).
  • Forgetting that a failed job's exception appears only when you call result() or exception() (errors can go unnoticed).
  • Too many workers hitting one server.
  • Lambdas and unpicklable arguments with ProcessPoolExecutor.
  • Leaving out the main guard with processes.
  • Updating shared data from many threads without a lock.

Key takeaways

  • concurrent.futures offers ThreadPoolExecutor (I/O-bound) and ProcessPoolExecutor (CPU-bound) with the same interface; use them in a with block.
  • executor.map returns results in input order and raises the first error; submit returns a Future for fine control.
  • future.result() returns the value or re-raises the job's exception; exception(), done(), cancel() and add_done_callback complete the picture.
  • as_completed yields futures as they finish; wait waits for first or all of a group; timeouts stop only your waiting.
  • Switching between threads and processes is a one-word change.

Practice

1. Which executor would you use to download 50 web pages? To compress 50 large files?

Show answer

ThreadPoolExecutor for the downloads (waiting); ProcessPoolExecutor for the compression (CPU-bound, though file I/O is part of it).

2. What does future.result() do if the job raised an exception?

Show answer

It re-raises that exception in the calling code.

3. What is the advantage of as_completed over looping through the futures in order?

Show answer

You handle each result as soon as it is ready, instead of waiting for earlier, slower jobs first.

4. Does future.cancel() stop a job that is already running?

Show answer

No. It only cancels a job that has not started yet; a running job cannot be interrupted.

5. Write code that squares 1 to 5 using 3 threads.

Show answer
with ThreadPoolExecutor(max_workers=3) as ex:
    squares = list(ex.map(lambda x: x * x, range(1, 5 + 1)))

6. Why did the thread pool not speed up the CPU-bound jobs?

Show answer

Only one thread can run Python code at a time (the GIL, lesson 20.6), so the calculations took turns.