Python multiprocessing Tutorial: Pool, ProcessPoolExecutor, Queues and Locks (2026)

Efficient Code Nov 27, 2026

Watch on YouTube

Your laptop has 8, 12 or 16 CPU cores, but a normal Python script uses only one of them. If your program spends its time calculating (parsing big files, resizing images, hashing, simulations, feature engineering or any pure-Python loop), the other cores sit idle. The multiprocessing module and its friendlier front end, concurrent.futures.ProcessPoolExecutor, fix that by running your function in several Python processes at the same time. Each process has its own interpreter and its own Global Interpreter Lock (GIL), so they really run in parallel. In this tutorial we measure the speed-up on a CPU-bound job, compare threads, processes and the new InterpreterPoolExecutor, use Pool.map, starmap, imap_unordered and chunksize, handle errors with as_completed, share data with a Queue, Value, Lock and Manager, and look at the start method change that arrived in Python 3.14. Everything ran on Python 3.15.2 with the standard library only, and every output block is the real output of the script above it.

When multiprocessing helps (and when it does not)

Use processes for CPU-bound work: code that keeps a core at 100% while it runs. For I/O-bound work, such as downloading pages, calling APIs or waiting for a database, threads or asyncio are lighter and usually enough, because the GIL is released while Python waits. Processes also have a cost: starting them takes milliseconds, and every argument and result is pickled and copied between processes. So the rule is simple: send few, large, CPU-heavy tasks to a process pool, not millions of tiny ones. Before you parallelise, measure where the time goes with a profiler, as shown in our guide to profiling Python runtime.

Setup

No installation is needed; multiprocessing and concurrent.futures ship with Python. InterpreterPoolExecutor needs Python 3.14 or newer. All examples import one CPU-bound helper from a small module. Worker functions must live in an importable module or at the top level of your script, because child processes import them by name.

uv python install 3.15      # or use any Python 3.14+
mkdir mp-demo && cd mp-demo  # save the files below here, then: python step1_speedup.py
"""CPU-bound helper shared by all demo scripts (must live in an importable module)."""
import math


def count_primes(limit: int) -> int:
    """Count primes below `limit` with plain trial division (pure Python, CPU-bound)."""
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, math.isqrt(n) + 1)):
            count += 1
    return count

Step 1: Serial vs threads vs processes vs interpreters

We run the same eight prime-counting jobs four ways. All executors in concurrent.futures share one interface, so switching between them is a one-word change. Note the if __name__ == "__main__": guard: with the spawn and forkserver start methods every child imports your script, and without the guard each child would try to start its own pool.

import os, sys, time
import multiprocessing as mp
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, InterpreterPoolExecutor
from work import count_primes

JOBS = [200_000] * 8          # eight identical CPU-bound jobs


def timed(label, run):
    start = time.perf_counter()
    result = run()
    print(f"{label:<24} {time.perf_counter() - start:6.2f} s   total primes = {sum(result):,}")


if __name__ == "__main__":
    print("Python", sys.version.split()[0], "| CPUs:", os.process_cpu_count(),
          "| GIL enabled:", sys._is_gil_enabled(), "| start method:", mp.get_start_method())
    timed("serial for-loop", lambda: [count_primes(n) for n in JOBS])
    with ThreadPoolExecutor(max_workers=8) as ex:
        timed("ThreadPoolExecutor", lambda: list(ex.map(count_primes, JOBS)))
    with ProcessPoolExecutor(max_workers=8) as ex:
        timed("ProcessPoolExecutor", lambda: list(ex.map(count_primes, JOBS)))
    with InterpreterPoolExecutor(max_workers=8) as ex:
        timed("InterpreterPoolExecutor", lambda: list(ex.map(count_primes, JOBS)))
Python 3.15.2 | CPUs: 8 | GIL enabled: True | start method: forkserver
serial for-loop            1.90 s   total primes = 143,872
ThreadPoolExecutor         2.36 s   total primes = 143,872
ProcessPoolExecutor        0.50 s   total primes = 143,872
InterpreterPoolExecutor    0.34 s   total primes = 143,872

The serial loop took 1.90 seconds. Threads were even slower (2.36 s) because only one thread can run Python bytecode at a time on the standard GIL build, and switching between them costs extra. The process pool finished in 0.50 seconds, a 3.8x speed-up on 8 cores, including the time to start the workers. InterpreterPoolExecutor, new in Python 3.14, was fastest at 0.34 seconds: it runs each worker in a separate sub-interpreter with its own GIL inside one process, so start-up is cheaper. It is still young, though, and many C extension packages do not support sub-interpreters yet, so ProcessPoolExecutor remains the safe default for real projects. If you want threads that run in parallel, the free-threaded build (python3.14t or python3.15t) removes the GIL; we compared that approach in Python no-GIL vs Rust.

Step 2: multiprocessing.Pool: map, starmap, imap_unordered and chunksize

multiprocessing.Pool is the older API, and it is still very common in existing code. map applies a function to every item and keeps the input order, starmap unpacks tuples into several arguments, imap_unordered yields results as soon as each one is ready, and apply_async runs one call in the background and returns an object with get().

import os, time
from multiprocessing import Pool
from work import count_primes


def square(x):
    return x * x


def power(base, exp):
    return base ** exp


def slow_task(n):
    time.sleep(0.05 * (5 - n))         # later items finish first
    return n, os.getpid()


if __name__ == "__main__":
    with Pool(processes=4) as pool:
        print("map:      ", pool.map(square, range(10)))
        print("starmap:  ", pool.starmap(power, [(2, 10), (3, 4), (10, 3)]))
        print("imap_unordered (finish order):", [n for n, _ in pool.imap_unordered(slow_task, range(5))])
        async_result = pool.apply_async(count_primes, (100_000,))
        print("apply_async:", async_result.get(timeout=30), "primes below 100,000")

        numbers = list(range(200_000))
        for chunk in (1, 1000):
            t = time.perf_counter()
            pool.map(square, numbers, chunksize=chunk)
            print(f"map 200,000 tiny tasks with chunksize={chunk:<5} {time.perf_counter() - t:.3f} s")
map:       [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
starmap:   [1024, 81, 1000]
imap_unordered (finish order): [3, 2, 4, 1, 0]
apply_async: 9592 primes below 100,000
map 200,000 tiny tasks with chunksize=1     7.550 s
map 200,000 tiny tasks with chunksize=1000  0.042 s

The imap_unordered line shows results in finish order (3, 2, 4, 1, 0), which is ideal for progress bars and for writing results to disk as they arrive. The last two lines are the most important lesson in this tutorial: sending 200,000 tiny tasks one by one (chunksize=1) took 7.55 seconds, while batching them 1,000 at a time took 0.042 seconds, about 180 times faster. Every task is a round trip through a pipe with pickling on both sides, so batch small tasks. Pool.map picks a chunk size automatically when you leave it out, but ProcessPoolExecutor.map defaults to chunksize=1, so set it yourself there when you have many small items.

Step 3: ProcessPoolExecutor with submit, as_completed and error handling

For new code, concurrent.futures is the recommended interface. submit() returns a Future, as_completed() yields futures as they finish, and future.result() re-raises any exception from the worker in the parent process, so one bad input does not kill the whole batch. An initializer runs once in every worker (good for loading a model or opening a connection), and max_tasks_per_child replaces a worker after a number of tasks, which helps with libraries that leak memory.

import os
from concurrent.futures import ProcessPoolExecutor, as_completed
from work import count_primes

CONFIG = {}


def init_worker(prefix):
    CONFIG["prefix"] = prefix                 # runs once per worker process


def check(limit):
    if limit < 0:
        raise ValueError(f"limit must be positive, got {limit}")
    return f"{CONFIG['prefix']} pid={os.getpid()} limit={limit:,} primes={count_primes(limit):,}"


if __name__ == "__main__":
    limits = [50_000, 150_000, -1, 100_000]
    with ProcessPoolExecutor(max_workers=3, initializer=init_worker, initargs=("[worker]",),
                             max_tasks_per_child=2) as ex:
        futures = {ex.submit(check, n): n for n in limits}
        for fut in as_completed(futures):
            n = futures[fut]
            try:
                print(fut.result())
            except ValueError as err:
                print(f"job {n} failed -> {type(err).__name__}: {err}")
job -1 failed -> ValueError: limit must be positive, got -1
[worker] pid=763302 limit=50,000 primes=5,133
[worker] pid=763305 limit=100,000 primes=9,592
[worker] pid=763306 limit=150,000 primes=13,848

The invalid job failed first and was reported cleanly, while the other three jobs still returned their results from different worker PIDs, each carrying the prefix set by the initializer. If a worker crashes hard (for example it is killed by the operating system for using too much memory), you get a BrokenProcessPool exception instead; since Python 3.15 its traceback includes the PID and exit code of the dead process, which makes these crashes much easier to debug. You can watch worker processes and their memory while a pool runs with psutil.

Step 4: Sharing data with Queue, Value, Lock and Manager

Processes do not share memory by default: a global variable changed in a child is not changed in the parent. When workers need to talk to each other, multiprocessing gives you queues for messages, Value and Array for shared numbers, Lock for safe updates, and Manager for shared Python dicts and lists.

from multiprocessing import Process, Queue, Value, Lock, Manager


def producer(q, n):
    for i in range(n):
        q.put(i * i)
    q.put(None)                                # sentinel: no more work


def consumer(q, out):
    total = 0
    while (item := q.get()) is not None:
        total += item
    out.put(total)


def add_unsafe(counter, times):
    for _ in range(times):
        counter.value += 1                     # read-modify-write: not atomic


def add_safe(counter, lock, times):
    for _ in range(times):
        with lock:
            counter.value += 1


def record(shared, name):
    shared[name] = len(name)


if __name__ == "__main__":
    q, out = Queue(), Queue()
    procs = [Process(target=producer, args=(q, 1000)), Process(target=consumer, args=(q, out))]
    for p in procs: p.start()
    for p in procs: p.join()
    print("Queue: sum of squares 0..999 =", out.get())

    for label, target, extra in (("without lock", add_unsafe, ()), ("with Lock()  ", add_safe, (Lock(),))):
        counter = Value("i", 0, lock=False)
        ps = [Process(target=target, args=(counter, *extra, 20_000)) for _ in range(4)]
        for p in ps: p.start()
        for p in ps: p.join()
        print(f"Value counter {label}: {counter.value:,} (expected 80,000)")

    with Manager() as manager:
        shared = manager.dict()
        ps = [Process(target=record, args=(shared, n)) for n in ("alpha", "beta", "gamma")]
        for p in ps: p.start()
        for p in ps: p.join()
        print("Manager dict:", dict(sorted(shared.items())))
Queue: sum of squares 0..999 = 332833500
Value counter without lock: 64,038 (expected 80,000)
Value counter with Lock()  : 80,000 (expected 80,000)
Manager dict: {'alpha': 5, 'beta': 4, 'gamma': 5}

The producer and consumer passed 1,000 numbers through a Queue, using None as a stop signal. The counter test shows a real race condition: four processes each added 1 twenty thousand times, but without a lock the result was 64,038 instead of 80,000, because counter.value += 1 is a read, an add and a write, and processes overwrote each other. With a Lock the total was exactly 80,000. A Manager dict is the easiest way to collect named results, but every access goes through a server process, so it is much slower than returning values from a pool. In practice, prefer returning results over sharing state.

Step 5: Start methods: fork, forkserver and spawn in Python 3.14+

A start method decides how a child process is created. fork copies the parent instantly, spawn starts a fresh interpreter, and forkserver starts one clean server process early and forks new workers from it. Since Python 3.14 the default on Linux and other POSIX systems is forkserver instead of fork (macOS and Windows already used spawn), because forking a process that has threads can deadlock. Python 3.15.1 adds a fallback to spawn when there is no writable temporary directory, for example in read-only containers.

import pickle, time
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor


def noop(_):
    return None


if __name__ == "__main__":
    print("available start methods:", mp.get_all_start_methods())
    print("default start method   :", mp.get_start_method())
    for method in ("fork", "forkserver", "spawn"):
        ctx = mp.get_context(method)
        t = time.perf_counter()
        with ProcessPoolExecutor(max_workers=4, mp_context=ctx) as ex:
            list(ex.map(noop, range(4)))
        print(f"start 4 workers with {method:<10} {time.perf_counter() - t:.3f} s")

    try:
        with ProcessPoolExecutor(max_workers=2) as ex:
            ex.submit(lambda x: x * 2, 21).result()
    except pickle.PicklingError as err:
        print("lambda ->", type(err).__name__ + ":", str(err).splitlines()[0])
available start methods: ['forkserver', 'fork', 'spawn']
default start method   : forkserver
start 4 workers with fork       0.010 s
start 4 workers with forkserver 0.064 s
start 4 workers with spawn      0.058 s
lambda -> PicklingError: Can't pickle <function <lambda> at 0x7f115c0a21f0>: it's not found as __main__.<lambda>

fork is the fastest to start (10 ms for four workers) but no longer the default, and you must request it with get_context("fork") if old code depends on inherited global state. forkserver and spawn cost about 60 ms here, which does not matter for long jobs. The last line shows the most common error after the 3.14 upgrade: with forkserver or spawn everything sent to a worker is pickled, and lambdas, nested functions and open file handles cannot be pickled. Move such functions to module level, as we did with work.py.

Common problems and fixes

  • RuntimeError about bootstrapping, or the script starts itself again: put the code that creates processes under if __name__ == "__main__":.
  • PicklingError: Can't pickle function: use a top-level function instead of a lambda or nested function, and pass data, not open files, sockets or database connections.
  • Code worked on Python 3.13 but globals are empty in workers on 3.14+: the default changed from fork to forkserver. Pass state as arguments or through an initializer, or explicitly use mp.get_context("fork").
  • Parallel version is slower than the loop: tasks are too small or too much data is copied. Increase chunksize, send file paths instead of big objects, or vectorise with NumPy first.
  • Jupyter notebook hangs: worker functions defined in a notebook cell cannot be imported by spawned children. Put them in a .py file and import them.
  • Too many processes: leave max_workers empty to use os.process_cpu_count(), or set it lower if each task needs a lot of memory.

multiprocessing, threads, asyncio or Dask?

Choose threads or asyncio for waiting on the network or disk, ProcessPoolExecutor for CPU-heavy pure Python on one machine, InterpreterPoolExecutor or the free-threaded build when you want to experiment with lower overhead, and a framework when the data no longer fits in memory or you need a cluster. Dask uses the same ideas with a larger scheduler; our introduction to parallel programming with Dask is the next step on that path.

Conclusion

For CPU-bound Python, a process pool is the simplest way to use every core: put the work in a top-level function, protect the entry point with if __name__ == "__main__":, and call ProcessPoolExecutor().map() or submit(). Batch small tasks with chunksize, return results instead of sharing state, use a Lock when you must share, and remember that Python 3.14+ uses forkserver on Linux, so everything you send to a worker must be picklable. In our test that was enough to turn 1.90 seconds into 0.50 seconds with a few lines of standard library code.

FAQ

Is multiprocessing faster than threading in Python? For CPU-bound work on the normal GIL build, yes: in step 1 processes were 3.8x faster than the loop while threads were slower. For I/O-bound work, threads are usually as fast and use less memory.

Should I use multiprocessing.Pool or ProcessPoolExecutor? Both work. Use ProcessPoolExecutor for new code because it shares one interface with threads and interpreters and handles errors through futures; keep Pool when you need imap_unordered or existing code already uses it.

How many workers should I use? Start with the default, the number of CPU cores available to the process, then measure. More workers than cores rarely helps CPU-bound jobs.

Does the GIL still matter in 2026? On the standard build, yes. The free-threaded build is officially supported since Python 3.14 but many packages are still catching up, so multiprocessing is still the most portable way to use all cores.

Tested versions: Python 3.15.2 (uv-managed CPython, standard GIL build) on Linux x86_64 with 8 CPU cores; standard library only, no pip packages.

Share:
Last updated: November 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices