Python Concurrency · Lesson 143 of 149

Python The GIL and Choosing a Concurrency Model

What you will learn

  • What the GIL is, and why CPython has one
  • What it does and does not prevent, with measurements
  • Why some C-based code runs in parallel in threads
  • How to choose between threads, processes and asyncio
  • Hazards that remain even with a GIL
  • Where the GIL is heading

1. What is the GIL?

CPython (the standard Python, from python.org) has a Global Interpreter Lock, the GIL: a lock that lets only one thread execute Python bytecode at a time, even on a computer with many cores. Threads take turns; the interpreter switches between them regularly (by default every 5 milliseconds, sys.getswitchinterval(), or when a thread starts waiting).

import sys

print("GIL enabled:", sys._is_gil_enabled(), "| switch interval:", sys.getswitchinterval(), "s")
GIL enabled: True | switch interval: 0.005 s

Why does it exist? CPython manages memory with reference counting (each object counts how many names refer to it, lesson 7.7). Updating those counts from several threads at once would need a lock on every single object, which would slow down ordinary single-threaded programs and complicate the C code that many Python libraries depend on. One global lock was a simple, fast and safe design choice, and it has stayed for decades.

The GIL is a detail of CPython, not of the Python language. Other implementations make other choices (for example, Jython and IronPython have no GIL, while PyPy has one of its own).

Quick check: does the GIL stop Python from running several programs in parallel?

No. It restricts threads within one Python process. Separate processes each have their own interpreter and their own GIL.

2. Measuring the effect

Four jobs of each type, run one after another, in four threads, and in four processes (from the check computer, with 8 cores):

--- pure Python loops
sequential                          1.85 s
4 threads                           1.95 s
4 processes                         1.04 s

The threads gave no speed-up (slightly slower, because of the switching), while the processes were almost twice as fast (four jobs on four cores should give a larger gain; process start-up and the machine's other activity take some of it; compare the 2.2 times in lesson 20.3).

Now work where the GIL is released. Whenever a thread is waiting for something outside Python (sleeping, the network, the disk), or is running certain C code that does not touch Python objects, it lets go of the GIL so that others can run:

--- waiting
sequential 4 x 0.5 s                2.00 s
4 threads                           0.50 s

Four waits overlapped completely, as in lesson 20.2. Remarkably, even heavy C-level computing can run in parallel in threads, if the library releases the GIL. Python's hashlib (checksums) and zlib (compression) do:

--- hashing 4 x 150 MB buffers (C code releases the GIL)
sequential                          0.35 s
4 threads                           0.12 s

--- compressing 4 x 30 MB (zlib releases the GIL)
sequential                          0.67 s
4 threads                           0.24 s

Threads were almost three times as fast in both. So the practical rule is not "threads never help with computing" but:

Threads do not speed up pure Python code. They do help whenever the time is spent waiting, or inside C code that releases the GIL.

Libraries such as NumPy, many image and database libraries, and hashlib/zlib release the GIL for their heavy operations. Check a library's documentation, and measure.

3. Choosing a model

Use the questions below, and measure the result (lesson 18.5).

Question If yes
Is the time mostly waiting for the network, disk or database? threads, or asyncio for very many connections
Is it pure-Python computing? processes (or a faster algorithm; lesson 18.5)
Is it heavy computing inside a library that releases the GIL (NumPy, hashing, compression)? threads can work; test it
Are there thousands of simultaneous connections? asyncio
Does the work split into independent pieces with small inputs and results? processes (copying the data costs time)
Is the task tiny? none of these: a plain loop is faster (lesson 20.3)
Do tasks need to share changing data a lot? rethink the design: share less, pass messages
Tool Parallel Python code? Overlaps waiting? Sharing data Typical cost
threading / ThreadPoolExecutor no (GIL) yes easy, needs locks low
multiprocessing / ProcessPoolExecutor yes yes copied, awkward high start-up and copying
asyncio no (one thread) yes, very efficiently easy, few races very low per task

A short decision helper makes the table concrete:

def choose_model(waiting, many_tasks=False, library_releases_gil=False, async_libs=False):
    """Suggest a concurrency tool. 'waiting' is True for I/O-bound work."""
    if waiting:
        if many_tasks and async_libs:
            return "asyncio"
        return "ThreadPoolExecutor"
    if library_releases_gil:
        return "ThreadPoolExecutor (the C code runs in parallel)"
    return "ProcessPoolExecutor"
download 20 web pages                                    -> ThreadPoolExecutor
serve 10,000 chat connections                            -> asyncio
count primes in pure Python                              -> ProcessPoolExecutor
hash 4 large files                                       -> ThreadPoolExecutor (the C code runs in parallel)
resize 500 images with a C library that releases the GIL -> ThreadPoolExecutor (the C code runs in parallel)

4. The GIL does not make your code safe

A common misunderstanding: "because of the GIL, I never need locks." Wrong. The GIL guarantees the interpreter's internal data stays consistent; it does not make your multi-step operations atomic. A thread can be switched out between any two bytecode steps, for instance between reading a counter and writing it back. Lesson 20.2 showed an unlocked counter losing most of its updates when a switch happened in that gap (2,000 and 2,295 instead of 8,000), and a locked one giving exactly 8,000.

Single operations on built-in types, such as list.append, are safe to call from several threads. Sequences of operations, such as "check then change", are not. Use locks, queues (lesson 20.2), or avoid sharing.

Other hazards that remain with or without a GIL:

  • Deadlocks: two threads each waiting for a lock the other holds.
  • Race conditions on files and databases: two programs writing the same file.
  • Order assumptions: concurrent tasks finish in unpredictable order.
  • Resource limits: too many threads, connections or open files.

Concurrent code is also hard to test and debug, because problems may appear only sometimes (lesson 18.4). Keep it simple and isolate it in small, well-tested parts.

5. Working around and beyond the GIL

Ways to get parallel speed in CPython today:

  1. Processes (multiprocessing, ProcessPoolExecutor).
  2. Libraries with compiled code (NumPy, pandas, scikit-learn, image tools) that do the heavy work outside Python.
  3. Write the hot spot in a compiled language (C, Cython, Rust through PyO3) that can release the GIL.
  4. Better algorithms, which often matter most (lesson 18.5).
  5. Sub-interpreters: since Python 3.12 each interpreter inside a process can have its own GIL, and a friendly standard-library interface for them is still being developed. An emerging option, not yet common.

Free-threaded Python. Python 3.13 introduced an experimental build option with the GIL removed ("free-threaded"), where threads can run Python code on several cores at once. Such builds exist but are experimental; many libraries are still being adapted, and single-threaded speed can suffer. The standard build, the one used for every check in this chapter, has the GIL enabled (sys._is_gil_enabled() was True). Programs written with proper locks and queues will carry over; programs that relied on luck will not. Read the current Python release notes before depending on this.

Worked example: a small benchmark to choose a model

Before committing to a design, measure the real work with each model on a few samples. This script uses the same helpers as the measurements in section 2 (each job function is defined at the top level so processes can use it).

import hashlib
import sys
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor


def py_loop(n):
    total = 0
    for i in range(n):
        total += i * i
    return total


def hash_big(data):
    return hashlib.sha256(data).hexdigest()[:8]


def sleepy(s):
    time.sleep(s)


def run(label, pool_cls, func, jobs, workers=4):
    start = time.perf_counter()
    with pool_cls(workers) as pool:
        list(pool.map(func, jobs))
    t = time.perf_counter() - start
    print(f"{label:<34} {t:5.2f} s")
    return t


def sequential(label, func, jobs):
    start = time.perf_counter()
    for j in jobs:
        func(j)
    t = time.perf_counter() - start
    print(f"{label:<34} {t:5.2f} s")
    return t


if __name__ == "__main__":
    print("GIL enabled:", sys._is_gil_enabled())
    jobs = [8_000_000] * 4
    sequential("pure Python, sequential", py_loop, jobs)
    run("pure Python, 4 threads", ThreadPoolExecutor, py_loop, jobs)
    run("pure Python, 4 processes", ProcessPoolExecutor, py_loop, jobs)

    bufs = [bytes(150_000_000)] * 4
    sequential("hashing, sequential", hash_big, bufs)
    run("hashing, 4 threads", ThreadPoolExecutor, hash_big, bufs)

    sequential("waiting, sequential", sleepy, [0.5] * 4)
    run("waiting, 4 threads", ThreadPoolExecutor, sleepy, [0.5] * 4)

Results from the check computer (the numbers are the ones printed in section 2):

Work Sequential 4 threads 4 processes
pure Python loops 1.85 s 1.95 s 1.04 s
hashing 4 x 150 MB 0.35 s 0.12 s not measured
compressing 4 x 30 MB 0.67 s 0.24 s not measured
waiting 4 x 0.5 s 2.00 s 0.50 s not measured
Reading Conclusion
threads did not help the Python loops the GIL: use processes, or a better algorithm
threads helped hashing and compression the C code releases the GIL, so threads suffice and avoid copying 150 MB to other processes
threads helped the waits overlapped waiting needs no extra cores
processes helped the loops but start-up and copying make them poor for small or data-heavy jobs

The buffers are blocks of zero bytes and the timings are specific to one computer. Run the benchmark on your own data and machine before deciding.

Common mistakes

  • Using threads for pure-Python computing and expecting a gain.
  • Assuming the GIL makes everything thread-safe.
  • Using processes when threads (or nothing) would do, wasting time on start-up and copying.
  • Deciding without measuring.
  • Ignoring library documentation about whether work releases the GIL.
  • Assuming every Python is the same: the GIL belongs to CPython; free-threaded builds are experimental.
  • Spreading shared mutable state across many threads.
  • Adding concurrency to code that is fast enough.

Key takeaways

  • The GIL lets only one thread run Python bytecode at a time in a CPython process; it protects the interpreter's memory management.
  • Threads therefore do not speed up pure-Python computing (1.85 s became 1.95 s), but they overlap waiting (2.00 s became 0.50 s) and C code that releases the GIL (hashing and compression ran about three times faster).
  • Processes give true parallelism for CPU-bound Python at a cost in start-up and copying; asyncio handles huge numbers of waiting connections cheaply.
  • The GIL does not make multi-step operations atomic: you still need locks, queues or no sharing.
  • Always measure; experimental free-threaded builds may change the picture in future.

Practice

1. What does the GIL prevent?

Show answer

Two threads of one CPython process from executing Python bytecode at the same instant.

2. Why were threads faster at hashing large buffers but not at a pure-Python loop?

Show answer

hashlib runs in C and releases the GIL while hashing, so threads run in parallel; the Python loop needs the GIL all the time.

3. True or false: with the GIL you never need a lock.

Show answer

False. The GIL does not make "read, then write" sequences atomic, so shared data still needs locks.

4. Which model would you pick for resizing 2,000 photos with pure-Python code?

Show answer

Processes (ProcessPoolExecutor), since it is CPU-bound pure-Python work. If an image library does the heavy lifting in C and releases the GIL, threads may do; measure.

5. Why might asyncio beat threads for 10,000 connections?

Show answer

A task costs far less memory than a thread, and switching happens only at await, so one thread can look after thousands of waiting connections.

6. Name two ways to get parallel speed-up for heavy computing in CPython today.

Show answer

Use processes, or use libraries/compiled code (NumPy, Cython, Rust extensions) that do the work outside the GIL.