Lesson · Concurrency Fundamentals
concurrent.futures
90 min readconcurrent.futures
`concurrent.futures` provides a common Executor/Future interface for thread, process, and, in Python 3.14, interpreter pools. It is often the simplest entry point for parallel mapping and background work.
Learning goals
- Submit one call at a time to a
ThreadPoolExecutorand treat the returnedFutureas a handle whose result arrives later. - Collect results in completion order with
as_completedand explain how that differs frommap's submission order. - Read an exception raised inside a worker through
future.result()and say when it surfaces. - Use the
with executor:block as the lifecycle boundary and describe what exiting it guarantees. - Compare thread, process and interpreter pools by what the work spends time on and what must cross their boundaries.
Mental model
An executor is a queue plus a fixed set of workers: submit and map place work and hand back handles, while result() is where waiting actually happens. Which order results arrive in is a choice, and that is the practical difference between map and as_completed.
Mental model
read it top to bottom
submit(work, n) one call enters the queue ↓ a Future returns a handle now, the value later workers run calls in parallel max_workers bounds how many run at once ↓ result() waits for that one call to finish value, or the worker's exception map preserves order; as_completed does not
Version note
Python 3.14 adds InterpreterPoolExecutor, a new executor option built on isolated interpreters.
Core idea
concurrent.futures reduces parallel work to two moves: hand an executor a callable and its arguments, then ask the returned Future for the outcome. The same interface covers threads, processes and, in 3.14, interpreter pools, so choosing among them becomes a question about the workload and the boundary that arguments must cross, not about a different API. Mapping is the bulk form of the same idea: map queues one call per item and yields results in submission order.
ThreadPoolExecutor
ThreadPoolExecutor manages a pool of worker threads behind the Executor API. It is usually appropriate for blocking I/O or library calls that release the GIL.
ProcessPoolExecutor
ProcessPoolExecutor runs callables in separate processes. Arguments and results must cross process boundaries, so serialization cost and picklability matter.
Future
A Future represents a computation that may not be finished yet. It provides result retrieval, exception propagation, cancellation state, and completion callbacks.
submit
submit schedules one call on an executor and immediately returns a Future. In concurrent.futures, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
map
map lazily applies a callable to items from one or more iterables. In concurrent.futures, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
as_completed
as_completed iterates futures in completion order rather than submission order. In concurrent.futures, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
Exceptions from workers
In concurrent.futures, Exceptions from workers names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Cancellation
Async cancellation is a cooperative control-flow event normally delivered as CancelledError at an await point. Cleanup code should release resources and usually re-propagate cancellation.
Executor shutdown
Executor shutdown controls whether the program waits for queued work and prevents new submissions. The executor context-manager form is usually the clearest lifecycle boundary.
Choosing thread vs process pools
This comparison separates Choosing thread from process pools in the context of concurrent.futures. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
InterpreterPoolExecutor (Python 3.14)
Python 3.14 adds InterpreterPoolExecutor, which combines worker threads with isolated interpreters. It can provide multi-core parallelism while staying in one process, but isolation and extension compatibility require deliberate design.
Isolation and serialization tradeoffs of interpreter pools
Isolation and serialization tradeoffs of interpreter pools converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
Python 3.14 example: interpreter pool
Interpreter workers are isolated. Treat argument/result transfer, extension compatibility, and task size as part of the performance model.
from concurrent.futures import InterpreterPoolExecutor def cpu_task(value): return sum(i * i for i in range(value)) with InterpreterPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, [10_000, 20_000, 30_000])) print(results)
Common mistakes
- Swallowing failures by never calling
result(): a failed worker stores its exception inside its future, so skipping retrieval turns a crash into a silent missing output. - Assuming submission order equals completion order:
as_completedyields by timing, so code that zips results back positionally without tracking indexes mismatches outputs and inputs. - Using a process pool with unpicklable work: lambdas, open handles and local closures cannot cross the boundary, so the pool refuses the submission.
- Leaving the executor lifecycle implicit: without the
withblock, the program can reach its last line while queued callbacks still run, and failures surface later, at interpreter shutdown.
Practice: Easy
- Run the submit example and print
future.done()for each future before anyresult()call; record the pattern you see. - Collect
(n, future)pairs, sort bynafteras_completedfinishes, and show the output now matches submission order. - Make
workraiseValueErrorforn == 3and print the error from that future'sresult()only.
Practice: Medium
- Run
executor.map(work, range(6))and thesubmit/as_completedpair on identical input, and name one task shape where each form is clearer. - Time the same eight sleeps under
max_workers=1andmax_workers=8, and argue from the two numbers what the pool size controls. - Move the squaring example to
ProcessPoolExecutor, define the function at module level, and record what changes when the first attempt uses a lambda.
Practice: Hard
- Design a batch pipeline (compute per item, then format) around an executor: choose the pool type from the workload, define per-item failure reporting, and show where the
withblock must sit for shutdown to be predictable. - Build a failure lab: submit a lambda to a process pool, call
result()on a worker that raised, and submit work after shutdown has begun; record each outcome and explain the mechanism. - Move the interpreter pool example to a CPU-heavy task and measure it against the thread and process pools on one machine; write a short rule for choosing among the three from your numbers.
Lesson checklist
- I can submit a call, keep its
Future, and retrieve the value or the exception through it. - I can explain what
as_completedchanges about the order results are handled in. - I can choose between
submitandmapfor a batch of work. - I can say what the
withblock guarantees on exit, and which pool type I would try for an I/O-heavy and a CPU-heavy batch.
Remember
An executor is a queue plus a bounded set of workers: `submit` and `map` place work and return handles, and `result()` is where waiting enters the picture. The same shape serves threads, processes and, in 3.14, interpreter pools, so the design question is always the workload plus the cost of crossing the boundary, and the lifecycle stays inside one `with` block.
Interview angles
What is the main purpose of **ThreadPoolExecutor**?+
ThreadPoolExecutor manages a pool of worker threads behind the Executor API. It is usually appropriate for blocking I/O or library calls that release the GIL.
What should you pay attention to when using **ProcessPoolExecutor**?+
ProcessPoolExecutor runs callables in separate processes. Arguments and results must cross process boundaries, so serialization cost and picklability matter.
How does **Future** fit into this lesson?+
A Future represents a computation that may not be finished yet. It provides result retrieval, exception propagation, cancellation state, and completion callbacks.
When does an exception raised inside a worker call actually surface to your code?+
It is captured inside that worker's Future at the moment it happens, and future.result() re-raises it when called; a future whose exception is never retrieved stays silent, so every submitted call should have its result checked or logged.