Skip to content

The GIL: what it locks and when it matters

Deep diveConcept

You split a slow Python loop across four threads and it gets no faster, yet threads clearly help a program that downloads files. Both come from one lock in CPython, the GIL: only one thread runs Python bytecode at a time, and a thread that waits on I/O lets go of it.

01 Four threads, no speed-up

This script runs the same CPU-bound function four times: one after another, then on four threads, then on four processes.

cpu_threads.py
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def count(n):
total = 0
for i in range(n):
total += i
return total
N = 10_000_000
def timed(label, run):
start = time.perf_counter()
run()
print(f"{label:<12}{time.perf_counter() - start:5.2f} s")
Text
$ python3 cpu_threads.py
1 thread 0.71 s
4 threads 0.75 s
4 processes 0.24 s

Those are real timings from one run with CPython 3.14 on a 14-core Apple Silicon laptop; yours will differ, but the shape will not. Four threads take as long as doing the work in a row, and slightly longer. Four processes use four cores and finish about three times faster.

02 One lock around the interpreter

The global interpreter lock is a mutex inside each CPython interpreter. A thread must hold it to execute Python bytecode or to touch Python objects. Threads are real operating-system threads and the OS will happily schedule them on different cores, but all but one of them will be waiting for the lock.

The reason is memory management. Every CPython object carries a reference count that changes each time a name, list or argument starts or stops pointing at it, which happens constantly. Keeping millions of those counts correct across threads would need an atomic operation or a lock per change. One big lock is simpler, keeps single-threaded code fast, and makes C extensions easy to write, because they can assume no other thread is touching Python objects while they run.

The GIL belongs to CPython, the standard interpreter. Jython and IronPython never had one, and PyPy has its own. Since 3.12 each sub-interpreter in one process can have its own GIL, and 3.13 added an optional free-threaded build with no GIL at all; more on that below.

03 How threads take turns

A thread does not keep the GIL forever. Since Python 3.2, a thread that wants the lock waits for a fixed switch interval and then asks the holder to let go. You can read the interval with sys.getswitchinterval(); it is 0.005 seconds by default.

Two threads sharing the GIL
Step 1 of 10
one CPython process, two threads
Thread AGILThread BNothing sent yet
  • this message

Two threads, A and B, both want to run a pure-Python loop. Nobody holds the GIL yet.

nobody running bytecode

The holder only notices the request between bytecode instructions, at points where the interpreter loop checks its flags. A single long call into C code, such as one huge sum() over a list, runs to the end before any other thread gets a turn.

04 Waiting on I/O lets others run

Blocking calls in the standard library, such as time.sleep, reading a file or socket, select and waiting on a subprocess, release the GIL before they block and take it back afterwards. The waiting happens in the kernel, where no Python objects are involved. So threads overlap their waits even though only one of them runs Python at a time.

io_threads.py
import time
from concurrent.futures import ThreadPoolExecutor
def wait(_):
time.sleep(1) # stands in for a network call
start = time.perf_counter()
with ThreadPoolExecutor(4) as pool:
list(pool.map(wait, range(4)))
print(f"4 waits of 1 s on 4 threads: {time.perf_counter() - start:.2f} s")
Text
$ python3 io_threads.py
4 waits of 1 s on 4 threads: 1.01 s

Four one-second waits finish in one second (a real run). Swap time.sleep(1) for an HTTP request and you get the same effect, which is why a thread pool of downloaders works well in Python.

CPU-bound work on threadsno fasterThreads take turns at the lock. The switching adds a little overhead on top.
I/O-bound work on threadsoverlapsEach thread drops the GIL while it waits, so the waits run side by side.
CPU-bound work on processesuses every coreEach process has its own interpreter and its own GIL. Arguments and results are pickled between them.

05 What releases the GIL, and what does not

C code can release the GIL around work that does not touch Python objects. Whether it does is up to each function, so it helps to know the common cases.

Typical behaviour in standard CPython
WorkHolds the GIL?Threads help?
A `for` loop in Python codeYes, the whole timeNo
`sum()`, `sorted()`, `json.loads()`Yes: C code, but it works on Python objectsNo
`time.sleep()`, file and socket reads, `subprocess` waitsNo, released while blockedYes
`hashlib` and `zlib` on large buffersNo, released while they crunch the bytesYes
Many NumPy operations on large arraysNo, released inside the numeric loopsOften

This is also why NumPy code can scale across threads when plain Python cannot: the heavy loop runs in C over raw numbers, with the GIL released.

06 The GIL does not make your code safe

One thread at a time sounds like no races. It is not. The GIL protects the interpreter’s own data, such as reference counts and the insides of a list or dict. It does not protect your invariants: a switch can happen between any two bytecode instructions, and one line of Python is usually several.

Text
$ python3 -c "import dis; dis.dis('counter += 1')"
0 RESUME 0
1 LOAD_NAME 0 (counter)
LOAD_SMALL_INT 1
BINARY_OP 13 (+=)
STORE_NAME 0 (counter)
LOAD_CONST 1 (None)
RETURN_VALUE

Read, add, write: three steps. If thread A reads 5, loses the GIL, and thread B reads 5 too, both write 6 and one deposit vanishes. This version puts a function call between the read and the write, which gives the interpreter a place to switch:

race2.py
import threading
balance = 0
def deposit(times):
global balance
for _ in range(times):
current = balance # read
current = current + 1 # work out the new value
log(current) # any function call is a chance to switch
balance = current # write back
def log(value):
pass
threads = [threading.Thread(target=deposit, args=(1_000_000,)) for _ in range(4)]
Text
$ python3 race2.py
3170184
$ python3 race2.py
2819701
$ python3 race2.py
2050278

Four threads made 4,000,000 deposits; real runs kept between about half and three quarters of them, and a different number each time. Wrap the read-modify-write in with lock: and it prints 4000000 every time.

A tight counter += 1 loop on recent CPython often happens to give the right total, because the interpreter only checks for a switch at some instructions. That is an implementation detail that has changed between versions and does not exist in the free-threaded build. Shared mutable state needs a threading.Lock, a queue.Queue, or no sharing at all.

07 Threads, processes, or no GIL

  • Threads (ThreadPoolExecutor): for work that mostly waits, such as HTTP calls, database queries and file reads. Cheap to start and they share memory.
  • Processes (ProcessPoolExecutor, multiprocessing): for CPU-bound Python code. Each has its own GIL. Starting them and pickling data between them costs time, so give each one a real chunk of work.
  • asyncio: for thousands of concurrent waits on one thread. No GIL contention at all, because only one thread exists, but every library on the path must be async.
  • C extensions that release the GIL (NumPy, many compression and crypto libraries): threads then do run in parallel inside the C code.

The free-threaded build removes the GIL. It arrived as an experiment in Python 3.13 (PEP 703) and became officially supported, but still optional, in 3.14. It is a separate executable, often named python3.14t, and sys._is_gil_enabled() reports whether the GIL is on. Pure-Python code typically runs a few per cent slower on one thread in that build, and C extensions must be built to support it, so check your dependencies before switching.

08 When it bites

ThreadPoolExecutor().map(resize_image, files)Threads for CPU-bound PythonIf resize_image is a pure-Python loop, the threads take turns and the job is no faster. Use a process pool, or a library that does the work in C and releases the GIL.
if key not in cache: cache[key] = load(key)Check-then-act across threadsEach dict operation is safe on its own, but two threads can both see the key missing and both call load. The GIL makes single operations safe, not sequences of them.
pool.map(work, huge_list_of_dicts)Processes with big argumentsEvery argument and result is pickled and copied between processes. When the data is large and the work per item small, the copying can cost more than the computation.
sys.setswitchinterval(0.0001)Tuning the switch intervalA shorter interval makes threads switch more often. It can help responsiveness, but it adds overhead and never adds parallelism to Python code.

09 Check yourself

Question

Eight threads each download a 10 MB file. Why do they finish much faster than one thread doing all eight?

Question

Two threads run a pure-Python loop. When does the waiting thread get a turn?

Question

Is counter += 1 from several threads safe because of the GIL?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?