Tutorials / Python: Intermediate to Advanced / Concurrency: threads versus processes

Concurrency: threads versus processes

14 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

Two kinds of slow

Programs are slow for two different reasons, and the cure depends on which one you have.

  • I/O-bound: the program waits for something outside, such as a network call, a database or a file. The CPU is mostly idle.
  • CPU-bound: the program is busy calculating: resizing images, parsing huge files, crunching numbers. The CPU is at 100 percent.

Mixing them up leads to wasted effort. Adding threads to a CPU-bound program will not make it faster.

The GIL

The standard CPython interpreter has a Global Interpreter Lock, the GIL. It lets only one thread run Python bytecode at a time within a process. That sounds terrible, but threads release the lock whenever they wait for I/O. So threads work well for I/O-bound jobs, because while one thread waits, another runs. For CPU-bound jobs, threads simply take turns and give no speed-up.

Python 3.13 also introduced an experimental free-threaded build that removes the GIL. It is not the default and many libraries are still catching up, so for production work today, plan as if the GIL exists.

Threads for I/O

import time
from concurrent.futures import ThreadPoolExecutor


def check_url(name: str) -> str:
    time.sleep(1)               # stands in for waiting on the network
    return f"{name}: ok"


names = [f"site{i}" for i in range(8)]

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=8) as pool:
    results = list(pool.map(check_url, names))
print(results[:2])
print(f"took {time.perf_counter() - start:.1f}s")      # about 1 second, not 8

Eight one-second waits finish in about one second, because the threads wait at the same time. ThreadPoolExecutor manages a group of worker threads for you. pool.map works like map but runs in parallel and returns results in the original order.

Processes for CPU work

To use several CPU cores for calculation, use separate processes. Each has its own interpreter and its own GIL.

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(n) for n 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, serial[0])

On a machine with four or more cores, the second timing is roughly a third to a quarter of the first. The last line prints True 17984, which is the number of primes below 200,000. The exact timings depend on your computer.

Why the if __name__ == "__main__" guard

On Windows and macOS, new processes are started by importing your script again from the top. Without the guard, each worker would try to start more workers, and you would get an error or an endless loop. Always protect the process-starting code with the guard. This is the most frequent failure people report with multiprocessing.

The costs of processes

Processes are heavier than threads. Starting one takes time, and arguments and results are copied between processes using pickling. Sending a huge list to a worker can cost more than the calculation. Give each worker a big enough job, such as a whole file or a large chunk, not a single tiny item. Also, lambdas and local functions cannot be pickled, so worker functions must be defined at the top level of a module.

Shared data and locks

Threads share memory, which is convenient and dangerous. Two threads updating one counter can lose updates, because count += 1 is several steps. Protect shared state with a threading.Lock, or better, avoid sharing: have workers return results and combine them in the main thread. With processes, memory is not shared at all, which avoids the problem but means you must pass data explicitly.

import threading

counter = 0
lock = threading.Lock()

def add_many():
    global counter
    for _ in range(100_000):
        with lock:
            counter += 1

Choosing

SituationUse
A few slow I/O callsThreadPoolExecutor
Hundreds or thousands of connectionsasyncio
Heavy calculation on many coresProcessPoolExecutor
Heavy numeric arraysNumPy first, then processes if needed
Nothing measured yetProfile first

Common mistakes

  • Using threads to speed up calculations.
  • Forgetting the main guard when using processes.
  • Creating a pool inside a loop, over and over. Create it once.
  • Ignoring exceptions. In a pool, an error appears when you read the result. Use future.result() or iterate over the map output so errors are not lost.

Try it yourself

Write a function that downloads a page, or simulates it with time.sleep(0.5), and run it for twenty names with a thread pool of five workers. Time it. Then write a CPU-heavy function, such as summing the digits of large factorials, and compare a thread pool against a process pool. Notice which one wins and why.

python
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(n) for n 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, serial[0])

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account