Skip to content
devtoolbox.cc

Python · Chapter 20 of 21

Python multiprocessing: process pools, queues, shared state

15 min study · Examples checked with Python 3.14 and 3.15 ·

Threads overlap waiting, but on the standard Python build they cannot run Python calculations on several CPU cores at once. Processes can: each one is a separate Python interpreter with its own memory, so a machine with eight cores can run eight of them in parallel. The price is that processes share nothing by default, so arguments and results are copied between them. This chapter shows the pool you will use for most work, the rules that make multiprocessing code run on every operating system, and the lower-level tools for passing data around.

A process pool for CPU-bound work

Save this as a file and run it from a terminal; multiprocessing examples don’t work in interactive shells:

import math
import time
from concurrent.futures import ProcessPoolExecutor

def count_primes(limit: int) -> int:
    return sum(1 for n in range(2, limit) if all(n % d for d in range(2, math.isqrt(n) + 1)))

def main() -> None:
    jobs = [300_000] * 4

    start = time.perf_counter()
    serial = [count_primes(n) for n in jobs]
    print(f"one process:   {time.perf_counter() - start:.2f}s")

    start = time.perf_counter()
    with ProcessPoolExecutor(max_workers=4) as pool:
        parallel = list(pool.map(count_primes, jobs))
    print(f"four processes: {time.perf_counter() - start:.2f}s")
    print(serial == parallel, parallel[0])    # True 25997

if __name__ == "__main__":
    main()

When this chapter was checked on a four-core machine, the loop took 2.05 seconds and the pool 0.67 seconds. Your numbers will differ, so run it yourself; with much smaller jobs the pool’s start-up cost eats the gain. ProcessPoolExecutor has the same interface as the thread pool from chapter 19 (map, submit, futures and as_completed), and an exception raised in a worker comes back when you ask for its result. By default it starts one worker per CPU core.

Why the main guard and module-level functions

Each worker process starts a fresh interpreter and imports your main module to find the function it should run. That has two consequences, and breaking either rule produces confusing errors.

First, the code that creates processes must sit under if __name__ == "__main__":. Without it, every worker would import the module, reach the pool creation again and try to start workers of its own; Python stops this with a RuntimeError.

Second, the function you send to a worker, its arguments and its return value must be picklable, because they travel between processes as bytes. Functions defined at module level are fine. Lambdas, functions nested inside other functions, and objects holding open files or locks are not.

How workers start depends on the platform. Windows and macOS use spawn (a brand-new interpreter). Since Python 3.14, Linux defaults to forkserver; older versions used fork, which copies the parent process and hides mistakes that later break on other systems. Writing code that works with spawn, as above, keeps it portable, and multiprocessing.get_context("spawn") lets you test that behaviour on Linux too.

Make the tasks big enough

Starting processes takes time, and every argument and result is copied. Sending a pool a million tiny tasks can be slower than a plain loop. Group work into chunks instead:

from concurrent.futures import ProcessPoolExecutor

def sum_of_squares(numbers: range) -> int:
    return sum(n * n for n in numbers)

def main() -> None:
    n, chunks = 2_000_000, 4
    size = n // chunks
    parts = [range(i * size, (i + 1) * size) for i in range(chunks)]
    with ProcessPoolExecutor() as pool:
        total = sum(pool.map(sum_of_squares, parts))
    print(total == sum(i * i for i in range(n)), total)   # True 2666664666667000000

if __name__ == "__main__":
    main()

Each worker receives a small range object, not two million numbers, and sends back one integer. Moving the data, not the computation, is often the bottleneck; pool.map(func, items, chunksize=500) does similar batching for you when items are many and small.

Queues and pipes between processes

When processes need to talk while they run, rather than just return a result, use a multiprocessing.Queue (any number of producers and consumers) or a Pipe (a connection between exactly two):

import multiprocessing as mp

def worker(tasks, results) -> None:
    while (item := tasks.get()) is not None:
        results.put((item, item ** 3))

def main() -> None:
    tasks, results = mp.Queue(), mp.Queue()
    procs = [mp.Process(target=worker, args=(tasks, results)) for _ in range(2)]
    for p in procs:
        p.start()
    for n in range(1, 6):
        tasks.put(n)
    for _ in procs:
        tasks.put(None)
    cubes = dict(results.get(timeout=5) for _ in range(5))
    for p in procs:
        p.join()
    print(sorted(cubes.items()))  # [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]

    parent, child = mp.Pipe()
    p = mp.Process(target=child.send, args=({"status": "ready"},))
    p.start()
    print(parent.recv())          # {'status': 'ready'}
    p.join()

if __name__ == "__main__":
    main()

The pattern mirrors the thread version: workers block on get() and stop at a None sentinel. Collect the results before joining the workers, because a process cannot exit while data it put on a queue is still waiting to be read. The timeout on results.get stops the parent from waiting forever if a worker crashes. Everything on a queue or pipe is pickled, so it is a copy, and unpickling data from an untrusted source can run code, so these channels are for your own processes only.

Shared state, if you must

Ordinary variables are not shared: a worker that appends to a global list changes its own copy. For a few shared numbers, multiprocessing.Value and Array live in shared memory and come with a lock:

import multiprocessing as mp

def add_many(counter) -> None:
    for _ in range(1000):
        with counter.get_lock():
            counter.value += 1

def main() -> None:
    counter = mp.Value("i", 0)          # "i" = C int
    procs = [mp.Process(target=add_many, args=(counter,)) for _ in range(4)]
    for p in procs:
        p.start()
    for p in procs:
        p.join()
    print(counter.value)                # 4000

if __name__ == "__main__":
    main()

The += 1 is again a read-modify-write and needs the lock. A multiprocessing.Manager() offers shared dictionaries and lists through a server process, at the cost of a round trip for every operation. Both are workable for small coordination tasks, but the cleanest design is usually the first one in this chapter: give each worker its input, let it return its result, and combine the results in the parent.

Python 3.14 also added concurrent.futures.InterpreterPoolExecutor, which runs tasks in separate interpreters inside one process. They have their own GIL each, so they run in parallel with less start-up cost than processes, though with similar restrictions on what can be passed between them.

Practice

Use a ProcessPoolExecutor to count primes below 50,000, 100,000, 150,000 and 200,000 in parallel with submit and as_completed, printing each limit with its count as soon as it is ready. Time it against a plain loop, then try max_workers=1 and max_workers=8.

Answer check: the counts are 5133, 9592, 13848 and 17984 in any completion order. One worker is about as fast as the plain loop plus start-up overhead. More workers than CPU cores brings no further speed-up for CPU-bound work, because the cores are already busy.

Summary

Use processes for CPU-bound Python work, through ProcessPoolExecutor first. Guard process creation with if __name__ == "__main__":, keep worker functions at module level, and remember that arguments and results are pickled copies. Make tasks large enough to repay the overhead, use queues and pipes for running conversations, and prefer returning results over shared state.

All Python chapters