Lesson · Multiprocessing
Process Pools
75 min readProcess Pools
A process pool amortizes worker startup and distributes independent CPU-heavy calls. Work size, serialization cost, chunking, and failure handling determine whether the pool actually improves throughput.
Learning goals
- Run a batch of independent calls through
ProcessPoolExecutor.mapand state why the results come back in input order. - Explain how a pool amortizes worker startup compared with starting a
Processper task. - Decide when CPU-bound work genuinely benefits from processes and when per-item overhead makes a plain loop faster.
- Tune
max_workersandchunksizeand describe what each changes about load balance and queue traffic. - Locate a worker exception in the parent and explain when it surfaces.
Mental model
A pool is a fixed crew of interpreters hired once, not a new worker per task. The crew is worth hiring only when each task is heavy enough that parallel execution outruns the per-item cost of serializing arguments and collecting results. If the items are tiny, the queue traffic is the workload and the sequential loop wins.
Mental model
read it top to bottom
pool.map(cpu_work, values) ↓ arguments are serialized and chunked to workers worker processes execute cpu_work in parallel ↓ exceptions and results travel back through the queue the parent consumes an iterator of results in input order
Core idea
A process pool keeps a fixed set of worker interpreters alive and streams many independent calls through them, so startup is paid once instead of per task. It pays off only when each call is CPU-heavy enough that parallel speedup beats the serialization and coordination overhead, and only when the work items are independent of one another. The pool also standardizes failure reporting: an exception raised in a worker resurfaces in the parent at the moment the corresponding result is retrieved.
ProcessPoolExecutor
ProcessPoolExecutor runs callables in separate processes. Arguments and results must cross process boundaries, so serialization cost and picklability matter.
Parallel map
pool.map(cpu_work, values) applies one function across an iterable by distributing the calls to the pool's workers. It returns an iterator of results in input order, regardless of the order in which workers finish, and accepting it (with list() or a loop) is what retrieves the values and re-raises any worker exception. chunksize= groups several items into one dispatch to a worker, trading queue round trips for coarser granularity.
CPU-bound workloads
CPU-bound code spends its time executing bytecode instead of waiting on IO, and in the default CPython build the GIL lets only one thread run that bytecode at a time. Separate processes each have their own interpreter, so they can occupy several cores at once; a pool of processes is the standard tool when the per-call work is dominated by computation.
Serialization cost
Cross-process or cross-interpreter execution can require arguments and results to be serialized or copied. For small tasks, that overhead can dominate the useful computation.
Chunking
Chunking groups several input items into one unit of work that is sent to a worker in a single dispatch. Larger chunks cut the number of queue round trips and the per-item serialization overhead, but they also reduce load balancing and make a job take longer to interrupt; the useful size depends on how uniform the items are and how many workers you run.
Worker failures
Worker exceptions must become visible to the coordinator, usually when a result is retrieved. Never let background failures disappear silently.
Walkthrough
cpu_work(value)is a pure function of one argument, which is exactly what makes it safe to run in another interpreter: nothing outsidevalueinfluences the result, so the answer does not depend on which worker gets it.ProcessPoolExecutor()starts a fixed crew of worker processes when thewithblock is entered, so the three calls share one startup cost instead of paying for a new process each.pool.map(cpu_work, [10_000, 20_000, 30_000])serializes each value, dispatches the calls, andlist(...)collects the sums in input order, soresults[0]is always the smallest workload even if a later call finished first; thewithblock then shuts the workers down before the finalprint.- Predict before running: what
resultscontains if one value raises, and at which line the parent notices.
Experiments to try
- Run the example, then run the same three calls in a plain loop; time both with
time.perf_counter()and state which cost the pool removed. - Raise a
ValueErrorinsidecpu_workfor one value only: find the exact line in the parent where the exception appears, and check whether the other results are still produced. - Rerun with a larger list of uniform values and compare
chunksize=1,chunksize=5, andmax_workers=2; write down which combination is fastest and connect the result to queue round trips and load balance. - Replace
ProcessPoolExecutorwithThreadPoolExecutor, keep everything else identical, and compare wall-clock time for the same values; explain the difference with the GIL.
Common mistakes
- Using a pool for tiny tasks: every item is serialized into a queue and its result travels back, and when the computation per item is a few microseconds those fixed costs dominate, so the parallel version is slower than the loop.
- Expecting results in completion order:
mapreorders them back to input order, so usesubmitplusas_completedwhen you genuinely need to react as work finishes. - Letting worker exceptions disappear: an exception is re-raised in the parent only when the corresponding result is retrieved, so calls whose results are never consumed fail silently.
- Assuming workers share memory: a counter or list mutated inside a worker stays in that worker's process, so pooled functions should return values instead of editing shared globals.
Practice: Easy
- Run the worked example and confirm
resultsmatches a plain loop over the same three values, element for element. - Change one value and predict both the new result and its position before running; explain why the position cannot change.
- Send a value that makes
cpu_workraise and record which parent line raises the exception; note that earlier results were already computed.
Practice: Medium
- For a list of twenty values, time
pool.mapagainst the sequential loop and find the point where the pool stops winning. - Run the same list with
chunksize=5and with the default; explain the difference in queue round trips and in how evenly the work splits across workers. - Use
submitandas_completedto print results in completion order for the same calls, then say whatmap's input order buys you in exchange.
Practice: Hard
- Build a batch scorer: a worker function that parses one line of data, a
mapover many lines, and an explicit policy for malformed lines (skip, default, or fail the batch); define result order and failure behavior before you run it. - Break the example in two ways: make the target a lambda and make one worker raise; for each, record the exception the parent sees, the line that raises it, and the mechanism behind the timing.
- Scale test: measure the same fixed workload at
max_workers=1,2, and4, plot the times, and explain the shape using startup cost, chunking, and the number of physical cores.
Lesson checklist
- I can explain why
mapreturns results in input order even though workers finish out of order. - I can pick
max_workersand achunksizefor a given workload and defend the choice. - I can find where a worker exception surfaces and why unconsumed results hide failures.
- I can decide from measurement (not habit) whether a pool beats a plain loop for a given task.
Remember
A process pool keeps a crew of worker interpreters alive and moves each independent call to them, so CPU-bound work can use several cores without paying startup per task. The tuning knobs are honest ones: worker count sets the ceiling, chunk size trades queue traffic against load balance, and every result that crosses the boundary carries serialization cost. Measure before trusting the pool, and consume every result you care about, because failures only surface when their value is retrieved.
Interview angles
What is the main purpose of **ProcessPoolExecutor**?+
ProcessPoolExecutor runs callables in separate processes. Arguments and results must cross process boundaries, so serialization cost and picklability matter.
What should you pay attention to when using **Parallel map**?+
pool.map distributes one function across the workers and returns results in input order, no matter which worker finished first. Consuming that iterator is what retrieves values and re-raises worker exceptions, and chunksize= decides how many items travel per dispatch.
How does **CPU-bound workloads** fit into this lesson?+
CPU-bound code keeps a single interpreter busy executing bytecode, and the GIL stops threads in one interpreter from doing that in parallel. Separate processes each own an interpreter, so a pool can spread the computation across several cores.
Why can the same `map` call be faster than a sequential loop for heavy values and slower for tiny ones?+
Every item is pickled and shipped to a worker, and its result comes back through a queue; those costs are fixed per item. Heavy computation hides them behind real parallel work, while tiny tasks spend more time in transit than computing, so the sequential loop wins.