Learn / Advanced / Lesson 3

Multiprocessing

12 min Tested on Python 3.15Updated By
In short

Multiprocessing runs work in several separate Python processes, each with its own interpreter and GIL, so CPU-heavy code really runs in parallel on several cores. Use concurrent.futures.ProcessPoolExecutor with map, keep the work in top-level functions, and always start pools under if __name__ == "__main__":.

A CPU-heavy task

Python
def count_primes(limit: int) -> int:
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

print(count_primes(10_000))
Output
1229

Running it on all cores

primes.py · run on your computer
import time
from concurrent.futures import ProcessPoolExecutor


def count_primes(limit: int) -> int:
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count


if __name__ == "__main__":
    limits = [200_000] * 4

    start = time.perf_counter()
    serial = [count_primes(x) for x in limits]
    print(f"one process:   {time.perf_counter() - start:.1f}s")

    start = time.perf_counter()
    with ProcessPoolExecutor() as pool:
        parallel = list(pool.map(count_primes, limits))
    print(f"process pool:  {time.perf_counter() - start:.1f}s")

    print(serial == parallel, parallel[0])
Output
one process:   1.2s
process pool:  0.6s
True 17984

This output comes from a 2-core machine, so the pool takes half the time. With 8 cores, expect it to be close to 8 times faster. The pattern holds for any heavy pure-Python function.

Rules that avoid headaches

  • Always create the pool under if __name__ == "__main__":. On Windows and macOS each worker re-imports your file, and without the guard it would start pools endlessly.
  • The function must be defined at the top level of a module, not inside another function or as a lambda — workers need to import it.
  • Arguments and results are copied between processes (pickled). Send small inputs, return small results; don't pass huge objects back and forth.
  • Processes don't share variables. Return values instead of changing globals.

Many small tasks: chunksize

squares.py · run on your computer
from concurrent.futures import ProcessPoolExecutor


def square(n: int) -> int:
    return n * n


if __name__ == "__main__":
    with ProcessPoolExecutor() as pool:
        results = list(pool.map(square, range(100_000), chunksize=5_000))
    print(sum(results))
Output
333328333350000

Sending work to a process has a cost. For thousands of tiny tasks, chunksize sends them in groups so the overhead doesn't eat the speed-up. For truly tiny work like this, plain Python or NumPy is faster than any pool.

When processes are worth it

Good fitPoor fit
Each task takes at least ~0.1 s of CPU timeTasks that finish in microseconds
Inputs and outputs are smallHuge data that must be copied to every worker
Pure Python calculationsWork already done in NumPy or pandas (they use fast C code)
Batch jobs: resizing images, parsing filesWaiting on networks — use threads or asyncio

Practice

Prepare work for a process pool. Write a top-level function word_count(text: str) -> int, then use the built-in map (exactly like pool.map) to count words in docs = ["one two", "three four five", "six"]. Print the list of counts and their total.

Expected output:
[2, 3, 1]
6
Your code

Quick check

1. Why do processes run CPU-bound Python code in parallel when threads don't?

2. Why is if __name__ == "__main__": needed with process pools?

3. Which task is a poor fit for a process pool?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →