Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Concurrency & parallelismSeniorCommonTroubleshooting

How can a race condition still occur in Python threads despite the GIL, and how does `threading.Lock` prevent it?

Answer

A compound operation like `counter += 1` is really a read-modify-write sequence (load the old value, add one, store the new value) rather than one indivisible step, so two threads can each read the same old value before either writes back the incremented result, and one increment is silently lost — a classic unsynchronized race regardless of exactly how that sequence is implemented internally. In the default GIL-enabled CPython build, only one thread executes Python bytecode at a time, but the interpreter can still switch which thread is running between the individual steps of that sequence, so the compound operation as a whole is not protected. `threading.Lock` (used as `with lock:`) ensures only one thread can execute the protected block at a time, making the whole read-modify-write sequence effectively atomic from the perspective of other threads that respect the same lock — and this fix is necessary regardless of whether a GIL is present, which matters because Python 3.14's free-threaded build removes the GIL entirely and needs exactly this kind of explicit locking even more than before.

Strong answer includes

  • compound read-modify-write operations like += are not one indivisible step
  • the interpreter can switch threads between the individual steps, losing an update
  • Lock serializes access so the sequence is effectively atomic, regardless of whether a GIL is present

Practical example

Protect shared state with a lock
from threading import Lock, Thread

counter = 0
lock = Lock()

def increment_many():
    global counter
    for _ in range(10_000):
        with lock:
            counter += 1

threads = [Thread(target=increment_many) for _ in range(4)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

print(counter)

The lock makes the read-modify-write update a critical section shared by all threads. Do not treat the GIL as a substitute for application-level synchronization.

Expected result: 40000.

#threading#race-conditions#locks

Sources

threading — Thread-based parallelismPython Software Foundation · Locks, thread safety and thread-local state