My account

Concurrency in Python

In the normal CPython build, the GIL lets only one thread run Python code at a time. So threads help when the program waits for the network or the disk, but they do not make pure Python math faster. For CPU work you use processes. Once you can tell I/O work from CPU work, and you know that the GIL does not protect your own data, choosing between threads, processes and asyncio becomes simple.

Not reviewedWritten with AI helpReading time: 16 minOnline shop examplePython 3.14 code

Author: bezzad

Contents

The problem: threads made one job faster and the other job not at all

Our online shop has two slow jobs every night:

  1. Shipping prices: ask 50 carrier APIs for their prices. Each call takes about one second, and most of that time is waiting for the network.
  2. The sales report: go over two million orders in pure Python and compute totals per product.

A developer put both jobs on a pool of 10 threads. The shipping job went from 50 seconds to about 5 seconds. The report job took the same time as before, sometimes a bit longer. Why did threads help one job and not the other? The answer is the GIL.

What is the GIL?

GIL means Global Interpreter Lock. In the normal (default) build of CPython, it is one lock for the whole interpreter.

  1. A thread must hold the GIL to run Python bytecode.
  2. So only one thread runs Python code at a time, even on a machine with 16 cores.
  3. A thread lets go of the GIL when it waits for I/O: a network call, a disk read, the time.sleep function. Then another thread can run.
  4. Many C extensions also let go of it during long work, for example parts of hashlib, zlib and NumPy. This depends on the library.

Why does CPython have it? It makes memory management (reference counting) simple and fast for single-threaded code, and it made C extensions easy to write.

I/O work: the waits overlapThread 1Thread 2Thread 3Done earlyCPU work: the threads take turnsThread 1Thread 2Thread 3Runs Python code (holds the GIL)Waits for I/O (no GIL)
With I/O work, threads wait at the same time, so the total time is short. With CPU work, threads only take turns on the GIL, so the total time does not get shorter.

I/O work vs CPU work

Before you choose a tool, ask one question: where does the time go?

  1. I/O-bound: the program mostly waits. HTTP calls, database queries, reading files. Threads or asyncio help, because the waiting happens at the same time.
  2. CPU-bound: the program mostly computes. Parsing big files, math in pure Python, image work in pure Python. Threads do not help in the normal build. Processes help, because each process has its own interpreter and its own GIL.

If you are not sure, measure. A profiler, or even a simple timer, shows whether the CPU is busy or idle while the job runs.

Threads for I/O: ThreadPoolExecutor

The concurrent.futures module gives a simple, high-level API. You give it functions, and it runs them on a pool of workers.

from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib.request

CARRIERS = [
    "https://carrier-a.example/price",
    "https://carrier-b.example/price",
]

def fetch_price(url: str) -> bytes:
    with urllib.request.urlopen(url, timeout=5) as response:
        return response.read()

def fetch_all_prices() -> dict[str, bytes]:
    prices: dict[str, bytes] = {}
    with ThreadPoolExecutor(max_workers=10) as pool:
        futures = {
            pool.submit(fetch_price, url): url for url in CARRIERS
        }
        for future in as_completed(futures):
            url = futures[future]
            try:
                prices[url] = future.result()
            except OSError as error:
                print(f"carrier failed: {url}: {error}")
    return prices
  1. The submit method starts the work and returns a Future at once. A Future is a promise of a result later.
  2. The as_completed function gives each Future when it finishes, in finish order.
  3. The result method returns the value, or raises the exception that happened in the thread. If you never call it, the error is silently lost.
  4. The with block waits for all work to finish before it exits.
  5. Always set a timeout on network calls. One stuck call can keep a worker busy forever.

The GIL does not protect your data

A common mistake: “Python has a GIL, so my code is thread-safe.” That is wrong. The GIL protects the interpreter’s own data, not your logic.

import threading

stock = {"shoes": 0}

def restock(times: int) -> None:
    for _ in range(times):
        stock["shoes"] += 1      # read, add, write: three steps
  1. The line with += is not one step. It reads the value, adds one, and writes it back.
  2. A thread switch can happen between these steps. Two threads read 41, both write 42, and one update is lost.
  3. The bug is rare, so it passes tests and shows up in production.

The fix is a lock around the whole read-and-write:

stock_lock = threading.Lock()

def restock(times: int) -> None:
    for _ in range(times):
        with stock_lock:
            stock["shoes"] += 1

Even better: do not share changing data between threads. Let each worker return its result, and combine the results in one place. The queue module is also thread-safe, and it is a good way to pass work between threads.

Processes for CPU work: ProcessPoolExecutor

For CPU-bound work, use processes. Each process is a separate Python interpreter with its own memory and its own GIL, so they really run in parallel on several cores.

from concurrent.futures import ProcessPoolExecutor
from collections import Counter

def sales_per_product(orders: list[tuple[str, int]]) -> Counter[str]:
    totals: Counter[str] = Counter()
    for sku, quantity in orders:
        totals[sku] += quantity
    return totals

def chunks(items: list, size: int):
    for start in range(0, len(items), size):
        yield items[start:start + size]

def build_report(orders: list[tuple[str, int]]) -> Counter[str]:
    report: Counter[str] = Counter()
    # one worker per CPU core by default
    with ProcessPoolExecutor() as pool:
        parts = chunks(orders, 100_000)
        for part in pool.map(sales_per_product, parts):
            report.update(part)
    return report

if __name__ == "__main__":
    orders = [("shoes", 1), ("hat", 2)] * 1_000_000
    print(build_report(orders).most_common(2))

Processes are not free. Know the costs:

  1. Data is copied. Arguments and results are pickled and sent between processes. Send big chunks of work, not one tiny item per call, or the copying costs more than the work.
  2. Functions must be picklable. A lambda or a function defined inside another function cannot be sent to a worker. Use a normal top-level function.
  3. The main guard is required. With the spawn and forkserver start methods, each worker imports your main module again. Without the check for the name “__main__”, the top-level code runs again in each worker and tries to start new processes, and Python stops with an error. Windows and macOS use spawn by default. Since Python 3.14, ProcessPoolExecutor on Linux uses forkserver by default, not fork.
  4. Each process uses its own memory. Ten workers mean ten interpreters.
Main processpool.map(...)combines the resultsWorker process 1own interpreter, own GILWorker process 2own interpreter, own GILWorker process 3own interpreter, own GILpickleBig chunks in, results back. The copying is the cost of real parallel work.
Each worker process has its own interpreter and its own GIL, so the work really runs in parallel. Arguments and results are pickled and copied between the processes.

Which tool when?

Work Good tool Why
Tens of HTTP or database calls ThreadPoolExecutor Simple. Threads wait at the same time.
Thousands of network connections asyncio One thread, very cheap tasks. Needs async libraries.
Pure Python math on big data ProcessPoolExecutor Each process has its own GIL and uses its own core.
NumPy or other C code that releases the GIL Often threads are enough The heavy work runs outside the GIL. Check the library docs.
A short script or a few calls No concurrency Simple code is easier to debug.

Free-threaded Python

Since Python 3.13, CPython can be built without the GIL. This is called the free-threaded build (PEP 703).

  1. In Python 3.13, it was experimental.
  2. In Python 3.14, it is officially supported (PEP 779), but it is still a separate, optional build. The normal build still has the GIL. The free-threaded interpreter has its own name, for example python3.14t.
  3. In this build, threads can run Python code on several cores at once. So CPU-bound threads can get faster.
  4. There are costs. Single-threaded code is somewhat slower than in the normal build, and every C extension you use must support the free-threaded build.
  5. Your locks are still needed. Without a GIL, data races in your code become more likely, not less.

Python 3.14 also added InterpreterPoolExecutor to concurrent.futures. It runs work in several interpreters inside one process. It is new, so check that your libraries support it before you use it.

Common mistakes

Mistake Result Better way
Threads for pure Python CPU work No speed-up, sometimes slower. ProcessPoolExecutor.
“The GIL makes my code thread-safe” Lost updates that are rare and hard to find. A lock, or no shared changing state.
Never calling the result method Errors in workers are silently lost. Call result, or check the exception of each Future.
One tiny item per process call Pickling costs more than the work. Send big chunks.
A lambda sent to a process pool A pickling error. A top-level function.
No main guard in the script Workers fail or start pools again. The check for the name “__main__”.
No timeout on network calls Stuck workers and a stuck job. A timeout on every call.

Summary in 6 lines

  1. In the normal CPython build, the GIL lets only one thread run Python code at a time.
  2. A thread lets go of the GIL while it waits for I/O. So threads help I/O-bound work.
  3. For CPU-bound pure Python work, use processes. Each one has its own GIL.
  4. The GIL does not protect your data. Use a lock, or do not share changing state.
  5. The concurrent.futures module gives one simple API for thread and process pools. Always read each result, so errors are not lost.
  6. Free-threaded Python is officially supported from 3.14, but it is an optional build, and the default build still has the GIL.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.