Sub topic 4
Shared state, race conditions, and locks
This chapter assumes you can start threads with threading.Thread and call start() and join(). It covers what goes wrong when several threads change the same data, and how to prevent it.
Why shared state is risky
Threads in one process share memory. A global variable, a list, or a dictionary is visible to every thread. That makes sharing data easy, but it also lets two threads change the same value at the same moment.
A race condition is a bug where the result depends on the order in which threads happen to run. The program may pass a hundred runs and fail on the next one.
Why `counter += 1` is not atomic
An operation is atomic if no other thread can see it half-finished. The statement counter += 1 looks like one step, but it is several:
- Read the current value of
counter. - Add 1 to it.
- Store the result back in
counter.
A thread can be paused between any two of these steps. If two threads both read 5, both compute 6, and both store 6, one increment is lost.
The GIL (Global Interpreter Lock) does not prevent this. It lets only one thread run Python bytecode at a time, but it can switch threads between bytecode steps. The later chapter on the GIL explains this in more detail.
Protecting shared state with a lock
A lock (threading.Lock) lets only one thread at a time enter a protected section. Other threads that try to enter wait until it is free. Use the lock in a with statement so it is always released, even if an exception occurs.
import threading
counter = 0
lock = threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock:
counter += 1
threads = [threading.Thread(target=work, args=(100_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # 400000With the lock, the output is always 400000. If you remove the with lock: line, the result can be lower and can change from run to run. How often it fails depends on your Python version and machine, so do not rely on a missing failure as proof of safety.
Common locking mistakes
- Forgetting to lock one access path. If one function locks and another reads or writes the same data without the lock, the data is still unprotected. Every access must use the same lock.
- Deadlock. Thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Neither can continue. Avoid it by always acquiring multiple locks in the same order.
- Re-acquiring a plain
Lockin the same thread. This blocks forever. Usethreading.RLockif the same thread must enter nested protected sections. - Assuming "check then act" is safe. Code such as
if key not in cache: cache[key] = compute()has a gap between the check and the write. Put both steps under one lock.
Avoiding shared state with `queue.Queue`
Often the better fix is to share less. A queue.Queue is a thread-safe container: its put() and get() methods handle locking internally. Threads can pass work and results through it without a lock of your own.
import queue
import threading
tasks = queue.Queue()
results = queue.Queue()
def worker():
while True:
item = tasks.get()
if item is None: # sentinel: no more work
break
results.put(item * item)
t = threading.Thread(target=worker)
t.start()
for n in range(5):
tasks.put(n)
tasks.put(None)
t.join()
print(sorted(results.get() for _ in range(5))) # [0, 1, 4, 9, 16]Here each value is owned by one thread at a time, so no race is possible on the items themselves.
Exercise
Two threads each run total += 10 1,000 times on a shared global total with no lock. Why might the final value be less than 20000, even though Python has a GIL?
Show answer
total += 10 is a read, an add, and a write. The GIL can switch threads between these steps, so both threads may read the same old value and one update is lost. The GIL protects the interpreter's internal state, not your multi-step operations. Wrapping the increment in with lock: fixes it.