What is the GIL in Python and how does it affect multithreading?
Quick answer
The Global Interpreter Lock (GIL) in CPython lets only one thread execute Python bytecode at a time, so threads do not speed up CPU-bound code but still help with I/O-bound work.
The GIL exists to keep CPython's memory management (reference counting) simple and safe. A thread releases it while waiting on I/O such as network calls and file reads, so many I/O-bound threads can overlap their waiting. For pure-Python CPU-bound loops, threads take turns and the program is no faster, sometimes slower.
To use multiple cores, use multiprocessing or concurrent.futures.ProcessPoolExecutor, which run separate interpreters, or push the heavy work into C extensions such as NumPy that release the GIL. Recent Python versions have an experimental free-threaded build that removes the GIL, but the default interpreter still has it.
Key points
- One thread runs Python bytecode at a time in CPython
- Threads are fine for I/O-bound work
- Use processes for CPU-bound work