On this page
  1. concurrent
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Collecting Results as They Finish (submit + as_completed)
  7. Gotchas & Boundaries

concurrent

Prev: compression | Up: stdlib_module | Next: configparser
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — concurrent
Tags: #public #python3 #stdlib


Import

import concurrent

Overview

Namespace package hosting concurrent.futures (ThreadPoolExecutor, ProcessPoolExecutor, Future, as_completed, wait). Reach for concurrent.futures as the cleanest high-level interface for parallel I/O (ThreadPoolExecutor) or CPU-bound fan-out (ProcessPoolExecutor) without managing raw threading or multiprocessing primitives manually.

Quick Start

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(lambda x: x * x, [1, 2, 3, 4]))
assert results == [1, 4, 9, 16]

Implementation Walkthrough

1. Collecting Results as They Finish (submit + as_completed)

Unlike pool.map() (which waits in submission order), as_completed() yields each Future the moment it finishes so you can handle per-item errors cleanly:

from concurrent.futures import ThreadPoolExecutor, as_completed

def double_positive(n: int) -> int:
    if n < 0:
        raise ValueError("negative")
    return n * 2

ok, errors = [], []
with ThreadPoolExecutor(max_workers=3) as pool:
    futures = {pool.submit(double_positive, n): n for n in (3, -1, 5)}
    for fut in as_completed(futures):
        try:
            ok.append(fut.result(timeout=5))
        except ValueError:
            errors.append(futures[fut])

assert sorted(ok) == [6, 10] and errors == [-1]

Gotchas & Boundaries

Linked from

Related notes