Full answer
python
import threading, time
def run(use_lock):
counter = {"n": 0}
lock = threading.Lock()
def work():
for _ in range(100):
if use_lock:
with lock:
v = counter["n"]; time.sleep(0); counter["n"] = v + 1
else:
v = counter["n"]; time.sleep(0); counter["n"] = v + 1
threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
return counter["n"]
print("without lock lost updates:", run(False) < 400)
print("with lock:", run(True))Output:
text
without lock lost updates: True
with lock: 400Four threads each add 1 to a shared counter many times, with a deliberate pause between reading and writing to widen the race. Without a lock, updates are lost and the final total is below the expected 400; with a threading.Lock around the read-modify-write, the total is exact. The GIL was held by one thread at a time throughout, yet the unlocked version still lost updates, because a thread can be switched out between the read and the write.
What the GIL means in practice:
- CPU-bound pure Python code does not run faster with threads; use
multiprocessingorconcurrent.futures.ProcessPoolExecutor. - I/O-bound code (network calls, disk) benefits from threads or asyncio, since waiting releases the GIL.
- NumPy and many C extensions release the GIL during heavy computation.
- Python 3.13 ships an optional free-threaded build (
python3.13t) without the GIL, still experimental; the standard build used here has the GIL.
The original audit answer said the GIL 'prevents race conditions'; the run shows why that is not true for application data.
python
import threading, time
def run(use_lock):
counter = {"n": 0}
lock = threading.Lock()
def work():
for _ in range(100):
if use_lock:
with lock:
v = counter["n"]; time.sleep(0); counter["n"] = v + 1
else:
v = counter["n"]; time.sleep(0); counter["n"] = v + 1
threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
return counter["n"]
print("without lock lost updates:", run(False) < 400)
print("with lock:", run(True))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Only one thread runs bytecode at a time in CPython
- The GIL does not make your code thread-safe
- Use locks for shared mutable state
- Threads help I/O-bound work
- Processes or C extensions for CPU-bound work
Common mistakes
- Claiming the GIL prevents race conditions
- Using threads to speed up CPU-bound loops
Follow-ups
- What is the free-threaded build in Python 3.13?
- When would asyncio beat threads?
Tips
- Separate interpreter safety from application safety