Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Concurrency & parallelismMiddleVery commonTheory

What is the Global Interpreter Lock (GIL), and why does it exist in the default CPython build?

Answer

The GIL is a single mutex inside the default CPython interpreter that allows only one thread to execute Python bytecode at a time, even on a machine with multiple CPU cores. It exists because CPython's memory management, particularly reference counting used for garbage collection, is not thread-safe by default, and the GIL was a simple, effective way to avoid data races on every object's reference count without requiring fine-grained locking throughout the interpreter. The practical consequence is that pure-Python, CPU-bound multi-threaded code does not get real parallel speedup on multiple cores, though I/O-bound threads still benefit because the GIL is released during blocking I/O calls.

Strong answer includes

  • a single mutex allowing only one thread to run Python bytecode at a time
  • exists because reference counting is not thread-safe without it
  • CPU-bound threads don't parallelize, I/O-bound threads still benefit

Practical example

Four Python threads each doing pure CPU-bound number crunching on a 4-core machine typically run barely faster than one thread, while four threads each waiting on network requests can genuinely overlap their waiting time.

#gil#concurrency#cpython-internals

Sources

Python support for free threadingPython Software Foundation · The GIL, the free-threaded build and its compatibility trade-offsPEP 703 — Making the Global Interpreter Lock OptionalPython Software Foundation · The technical proposal behind the free-threaded CPython build