Q&A-1Explain precisely what the GIL serializes and which application invariants it does not protect.
Answer
The 90-second answer. In a standard GIL-enabled CPython build, the GIL is one mutex per interpreter that a thread must hold to execute Python bytecode. It serializes bytecode execution, not your program's logic. It does not make x += 1 atomic, it does not protect check-then-act sequences, and it does not protect invariants that span more than one object. It does protect reference counts and the internal consistency of the built-in containers. If you need mutual exclusion for an application invariant, you still need a threading.Lock.
Mechanism. A thread holds the GIL and drops it every sys.getswitchinterval() seconds, 5 ms by default, so another thread can run. It also releases it around blocking I/O (file, socket) and inside C extensions that call Py_BEGIN_ALLOW_THREADS (numpy, hashlib, zlib, most DB drivers). A switch can land between any two bytecodes. That is the whole granularity: one bytecode.
Worked trace. counter += 1 on a global is not one bytecode. In CPython 3.12, dis.dis(bump) for
counter = 0
def bump():
global counter
counter += 1emits this sequence (offsets vary by version; the sequence is what matters):
| # | bytecode | effect on stack |
|---|---|---|
| 1 | LOAD_GLOBAL counter | push 0 |
| 2 | LOAD_CONST 1 | push 1 |
| 3 | BINARY_OP 13 (+=) | pop 1 and 0, push 1 |
| 4 | STORE_GLOBAL counter | pop 1, counter = 1 |
Four bytecodes, so a switch can land between any two. Two threads, counter starts at 0:
| step | T1 | T2 | counter |
|---|---|---|---|
| 1 | LOAD_GLOBAL → 0 | 0 | |
| 2 | (switch) | 0 | |
| 3 | LOAD_GLOBAL → 0 | 0 | |
| 4 | LOAD_CONST 1 | 0 | |
| 5 | BINARY_OP → 1 | 0 | |
| 6 | STORE_GLOBAL 1 | 1 | |
| 7 | LOAD_CONST 1 | 1 | |
| 8 | BINARY_OP → 1 | 1 | |
| 9 | STORE_GLOBAL 1 | 1 |
Final value 1, not 2. A lost update, with no exception and no warning.
Invariants the GIL does not protect.
- Read-modify-write on shared state: counters, accumulators,
total += row.amount. - Check-then-act (TOCTOU):
if key not in cache: cache[key] = expensive(). Two threads both miss, both compute, one result is discarded.dict.setdefaultis atomic; the surrounding pattern is not. - Multi-object invariants:
a.balance -= x; b.balance += x. A concurrent reader can observe the money gone from both accounts. - Lazy initialization:
if _client is None: _client = connect(). Two connections, one leaked. - Iteration while another thread mutates:
RuntimeError: dictionary changed size during iteration. - Anything inside a C extension that released the GIL: numpy array writes, hashlib updates on a shared buffer.
What it does protect. Reference counts (Py_INCREF/Py_DECREF), so an object is not freed mid-use; the internal consistency of list, dict and set; and the atomicity of a single bytecode or a single non-releasing C call. d[k] = v is one STORE_SUBSCR; lst.append(x) is one C call that never drops the GIL: both are atomic. d[k] = d.get(k, 0) + 1 spans several bytecodes and is not.
Alternatives and when threads are wrong. CPU-bound work: threads give you roughly one core total, plus GIL convoy overhead from switching every 5 ms. Use multiprocessing or a C extension that releases the GIL. I/O-bound work: threads are fine, the GIL is released during the syscall. Many concurrent connections: asyncio avoids GIL contention entirely but needs async-aware libraries. Free-threaded CPython (PEP 703) shipped as an experimental --disable-gil build in 3.13 and a supported build in 3.14; it removes the GIL with per-object locks and biased reference counting, at a single-thread throughput cost.
Detection. Force the race: sys.setswitchinterval(1e-6) and run the stress test, asserting the invariant after every iteration. For free-threaded builds, run under ThreadSanitizer. A RuntimeError on dict iteration in production logs is the same class of bug already firing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.