GIL

Python interview question · Hard difficulty

What is the GIL and what are its practical consequences?hard

Status
✓
Type
conceptual
Topic
gil
Frequency
common
Tags
GIL, threading, concurrency, CPython, multiprocessing
Answer

The Global Interpreter Lock ensures only one CPython thread executes Python bytecode at a time, even on multi-core machines. It exists because CPython uses reference counting for memory management, and concurrent updates to reference counts would cause race conditions.

Explanation

The GIL is released during I/O operations, so threads genuinely improve I/O-bound work like API calls and file reads. For CPU-bound work requiring true parallelism, use multiprocessing — each process has its own interpreter and its own GIL. NumPy and PyTorch release the GIL internally during their C-level computation, so threading works well with them. Python 3.13 introduced an experimental no-GIL build. The GIL also explains why FastAPI uses async def for I/O routes and offloads blocking sync routes to a threadpool.

Follow-upWhy can Python threads still improve I/O-heavy programs?
Follow-upWhen would you use multiprocessing over threading?
Follow-upHow does the GIL affect FastAPI route handling?