Skip to main content

5. Global Interpreter Lock (GIL)

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously.


Implications

  • Simplifies memory management.
  • Limits true parallelism with threads in CPython.

Example

import threading

def worker():
for _ in range(10**6):
pass

threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()

Even with 4 threads, execution is limited by the GIL.


Workarounds

  • Use multiprocessing for CPU-bound tasks.
  • Use threading or async for I/O-bound tasks.

Wrap-Up

The GIL is a CPython limitation to be aware of when designing concurrent programs.