The GIL: what it locks and when it matters
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.
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.
- this message
Two threads, A and B, both want to run a pure-Python loop. Nobody holds the GIL yet.
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.
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.
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.
| Work | Holds the GIL? | Threads help? |
|---|---|---|
| A `for` loop in Python code | Yes, the whole time | No |
| `sum()`, `sorted()`, `json.loads()` | Yes: C code, but it works on Python objects | No |
| `time.sleep()`, file and socket reads, `subprocess` waits | No, released while blocked | Yes |
| `hashlib` and `zlib` on large buffers | No, released while they crunch the bytes | Yes |
| Many NumPy operations on large arrays | No, released inside the numeric loops | Often |
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.
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:
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.