Sub topic 9
Protecting shared state with locks
This chapter assumes you know the threading module, what a race condition is, and the basic idea of a lock. It builds on the previous chapter, which showed that operations like counter += 1 are not atomic.
Why locks matter more without the GIL
Under the GIL, only one thread runs bytecode at a time. Many races still existed, but they appeared rarely, because the interpreter switched threads only at certain points. On a free-threaded build, threads run truly in parallel. A race that once showed up once in a million runs can now show up in seconds.
A lock (also called a mutex) makes a block of code run in only one thread at a time. The code inside such a block is called a critical section. Any thread that reaches a held lock waits until the owner releases it.
Fixing the lost-update bug
The statement counter += 1 is really three steps: read the value, add one, write the result back. Two threads can read the same value and both write back the same result, so one update is lost. A lock around the whole read-modify-write fixes this.
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) # 400000Use with lock: rather than calling acquire() and release() by hand. The with statement releases the lock even if the block raises an exception.
Choosing the lock's scope
Every lock has a cost, so the scope matters.
- Too narrow: if you lock only the write but not the read, the race remains. Guard the whole read-modify-write sequence.
- Too wide: if you hold a lock while doing slow work, such as I/O or heavy computation, other threads wait and you lose the parallelism you wanted.
A good rule is to keep critical sections short. Do the expensive work outside the lock, then take the lock only to publish the result.
Also keep one lock per piece of shared data, and document which lock guards what. A common pattern is to put the data and its lock in the same object.
import threading
class Stats:
def __init__(self):
self._lock = threading.Lock()
self._total = 0
self._count = 0
def add(self, value):
with self._lock:
self._total += value
self._count += 1
def mean(self):
with self._lock:
return self._total / self._count if self._count else 0.0mean also takes the lock. Without it, a reader could see _total updated but _count not yet, and compute a wrong average.
Other primitives
| Primitive | Use it when |
|---|---|
| `threading.Lock` | One thread at a time may enter a section. |
| `threading.RLock` | The same thread may need to take the lock again, for example in a method that calls another locked method. |
| `threading.Semaphore` | Up to N threads may enter at once, such as limiting open connections. |
| `threading.Condition` | A thread must wait until some state becomes true. |
| `threading.Event` | One thread signals many others that something happened. |
Common errors
- Deadlock. Thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Neither moves. Prevent this by always taking multiple locks in the same order.
- Re-acquiring a plain
Lock. A thread that already holds aLockand tries to take it again blocks forever. UseRLockif that is intended. - Separate locks for related data. If two values must change together, one lock must guard both.
- Assuming a test proves safety. A passing run does not show the absence of races. Run threaded tests many times.
Exercise
Two threads each run total += amount on a shared global, protected by two different Lock objects (each thread uses its own lock). Is the update safe? Why or why not?
Show answer
No. A lock only excludes threads that use the same lock object. With separate locks, both threads can enter their critical sections at once, so the read-modify-write can interleave and lose updates. Both threads must use one shared lock.