Stop 14 · Advanced PythonTopics · 5/8

multiprocessing

Part of the Python Roadmap

In short

Your laptop probably has 4 to 16 CPU cores, and a normal Python script uses just one. multiprocessing puts the rest to work on heavy jobs like crunching numbers or processing images.

multiprocessing and ProcessPoolExecutor run code in separate processes, each with its own interpreter and GIL, so CPU-heavy work can use every core. Data passed between processes must be picklable.

The jaadu wheels a trolley of answer-sheet bundles down a corridor, dropping one bundle into each of several small rooms where a teacher sits marking at a separate desk.

Think of it like this

Exam paper evaluation centre

One teacher checking 2,000 answer sheets takes weeks. The board splits the pile into bundles and sends them to separate rooms, each with its own teacher, desk and red pen. Teachers don't share desks, so they never get in each other's way. At the end, the marks from each room are collected and combined.

Watch it happen

How Pool.map splits the work

Split into chunks
Pickle and send
Workers compute
Send results back
Combine

1/5The main process divides 1 to 1,000,000 into four ranges.

The big ideas

What you need to know

Real parallelism

Each process has its own Python interpreter and its own GIL, so pure Python code really runs on several cores at once.

The main guard

Always start processes under if __name__ == "__main__":. Without it, workers can re-run your startup code and crash or loop.

Data must be picklable

Arguments and results travel between processes as pickled bytes. Plain functions, numbers, lists and dicts work. Lambdas and open files don't.

Big chunks win

Sending data costs time. Give each worker a large piece of work and return small results.

See it in code

Walk through the code

python
1from multiprocessing import Pool, cpu_count2 3def collatz_steps(n: int) -> int:4    steps = 05    while n != 1:6        n = n // 2 if n % 2 == 0 else 3 * n + 17        steps += 18    return steps9 10def longest_in_range(bounds: tuple[int, int]) -> tuple[int, int]:11    lo, hi = bounds12    best = max(range(lo, hi), key=collatz_steps)13    return best, collatz_steps(best)14 15if __name__ == "__main__":16    size = 250_00017    chunks = [(start, start + size) for start in range(1, 1_000_001, size)]18 19    with Pool(processes=cpu_count()) as pool:20        results = pool.map(longest_in_range, chunks)21 22    number, steps = max(results, key=lambda r: r[1])23    print(f"Up to one million, {number} takes the most steps: {steps}")

1/5A CPU-heavy pure Python function. Perfect for processes, useless for threads.

Finds the number up to one million with the longest Collatz sequence, using every CPU core. ProcessPoolExecutor from concurrent.futures works the same way.

Save yourself the pain

Common mistakes

Oops

Forgetting if __name__ == "__main__": and seeing errors or endless processes on Windows or macOS.

Do this instead

These systems start workers by importing your file again, so code that creates the pool must sit under the main guard.

Oops

Passing a lambda or a nested function to pool.map.

Do this instead

They can't be pickled. Define the worker function at the top level of the module.

Oops

Expecting a global variable changed in a worker to change in the main process.

Do this instead

Each process has its own memory. Return results, or use a Queue or Manager to share state.

Your mission

Use every core

~30 min

Quick check

Why can't you pass a lambda directly to Pool.map?

Go deeper

  1. 1Speed up a CPU-heavy function across cores with ProcessPoolExecutor.
  2. 2Put process-starting code under the __main__ guard, which Windows requires.
  3. 3Compare the run time with a single-process version.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge