Skip to the page

Concurrency · core

The GIL and thread safety

The Global Interpreter Lock lets one thread run Python bytecode at a time in a standard CPython process. It helps threads with I/O but does not make your code thread-safe, and the free-threaded build is optional.

The notes

What you must know

  • The GIL lets one thread at a time run Python bytecode in a CPython process. It protects the interpreter's internals, such as reference counts.
  • The GIL is released while waiting on sockets, files and sleep, and many C libraries release it during heavy work, so threads help with I/O.
  • CPU-bound pure Python does not scale with threads. Use processes, C extensions or subinterpreters.
  • The GIL does not make your code thread-safe. hits["count"] += 1 is read, add, store; a switch in between loses an update.
  • A test that prints the right total on your laptop proves nothing. Switch points and Python versions change how often the bug shows.
  • Fixes: a threading.Lock around the update, per-thread local counts added at the end, or a queue.Queue to one counting thread. Do not rely on "atomic in CPython".
  • Free-threaded build: PEP 703; optional but officially supported since 3.14 (PEP 779). The default build still has the GIL.
  • On the free-threaded build, importing an extension that does not declare support turns the GIL back on. sys._is_gil_enabled() tells you. Say only what the official docs say.

The red pen

Common traps: mistake → fix

  • Mistake: The GIL makes Python code thread-safe

    Fix: only the interpreter internals are protected.

  • Mistake: Threads are useless in Python

    Fix: they are good for I/O-bound work.

  • Mistake: The GIL was removed in 3.13

    Fix: the default build still has it; free-threading is optional.

  • Mistake: It printed 800,000 every time, so it is safe

    Fix: luck; a race can still appear.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the GIL and what does it stop?
  2. Why do threads still help with downloads?
  3. Eight threads run hits["count"] += 1 100,000 times each. Is it safe?
  4. How do you fix that counter in three ways?
  5. What is the status of free-threaded Python today?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview