Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · The Global Interpreter Lock (GIL)

The Global Interpreter Lock (GIL)

On this pageWaiting and ComputingThe Implementation Matters

CPython is the standard Python implementation used by these examples. In a conventional GIL-enabled CPython process, the Global Interpreter Lock allows only one thread to execute Python bytecode at a time. This helps coordinate access to interpreter-managed objects; it does not make every operation on shared application data safe.

Waiting and Computing

A thread can release the GIL while waiting for supported I/O operations. Other threads can then make progress. That is why threads can help a program overlap network waits or file operations.

CPU-bound loops written in Python usually do not gain multi-core execution from threads in a GIL-enabled process. Separate processes can run such work in parallel, but creating workers and transferring data have costs. Some numerical libraries run native code that releases the GIL, so they need separate measurement.

The Implementation Matters

The GIL is not a rule of the Python language. CPython offers optional free-threaded builds from Python 3.13, and extensions can affect whether the GIL is enabled. The examples here assume a conventional GIL-enabled interpreter unless stated otherwise. See Python’s free-threading documentation.

Choose from the workload: threads can overlap waiting; processes can distribute Python computation; asynchronous I/O lets tasks cooperate through an event loop. Measure the actual program rather than assuming more workers are faster.

We will begin with a small thread-pool simulation, then run a portable process-pool example.