Dispatch Serializable Work to Process Pools
Core idea
ProcessPoolExecutor runs callables in worker processes. Use a top-level importable function and picklable arguments and results. Process startup and serialization have costs, so group sufficiently large independent CPU jobs. Map retains input order, not necessarily execution order. Run the following as saved scripts with the main guard.
from concurrent.futures import ProcessPoolExecutorfrom multiprocessing import get_contextdef score(batch): return sum(x*x for x in batch)if __name__ == '__main__': with ProcessPoolExecutor(max_workers=2, mp_context=get_context('spawn')) as pool: print(list(pool.map(score, [[1, 2], [3, 4]])))Each batch is independent and the map result follows input order. This tiny workload illustrates the API, not a speedup.
Expected output:
[5, 25]Collect a failed future
from concurrent.futures import ProcessPoolExecutorfrom multiprocessing import get_contextif __name__ == '__main__': with ProcessPoolExecutor(max_workers=1, mp_context=get_context('spawn')) as pool: good = pool.submit(int, '12') bad = pool.submit(int, 'x') print(good.result()) try: bad.result() except ValueError: print('invalid')The future propagates the worker exception to the parent.
Expected output:
12invalidCommon mistake
Do not pass open handles, local closures or lambdas expecting them to serialize automatically. Never call executor or future methods from a callable submitted to that same process executor.
Practice
Dispatch three independent batches and compare results with a sequential implementation. Explain why these tiny examples do not establish better performance.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Process pools
Check your understanding of process pools.
What is printed?
import picklepayload=[2,4]print(pickle.loads(pickle.dumps(payload)))What is printed?
from concurrent.futures import Futuref=Future(); f.set_result(9)print(f.result())What is a suitable task for a process pool?
What can dominate very small jobs?