Sub topic 9
Protecting shared state with locks
This chapter assumes you know basic Python and threading, and that you have seen the idea of a race condition. It also assumes you have read the earlier chapters on free-threaded builds and data races. Here you will learn how to use locks to make compound updates safe, how to choose lock granularity, and how to avoid deadlocks.
Why locks matter more without the GIL
In a standard build, the GIL lets only one thread run bytecode at a time. That hides many races. Even there, counter += 1 is not atomic, because it is a read, an add, and a write. The interpreter can switch threads between those steps. Races were rare enough that buggy code often survived testing.
On a free-threaded build, threads really run at the same time on different cores. The window for a race is much wider, and bugs that stayed hidden for years can show up quickly.
Built-in containers such as list and dict protect their own internal state. A concurrent append will not corrupt the list or crash the interpreter. That guarantee covers single operations only. It does not cover a sequence of operations that your program treats as one logical step.
A lock fixes this. A lock (also called a mutex) lets only one thread at a time hold it. Code that runs while holding the lock is a critical section. Every thread that touches the shared state must take the same lock, or the protection is lost.
The basic pattern: `with lock`
threading.Lock is the primitive you will use most. Use it as a context manager so the lock is always released, even when 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) # 400000Without with lock, the final value would often be below 400000. The exact number would change from run to run.
Avoid calling lock.acquire() and lock.release() by hand. If code between them raises an exception and you did not use try/finally, the lock stays held and every other thread waits forever.
The diagram below shows two threads competing for one lock.
Check-then-act needs one lock around both steps
The most common mistake is a check followed by an action. Each step may be safe alone, but another thread can run between them.
import threading
cache = {}
cache_lock = threading.Lock()
def get_or_create(key, factory):
with cache_lock:
if key not in cache:
cache[key] = factory()
return cache[key]Without the lock, two threads could both see that key is missing, both call factory(), and one result would overwrite the other. If factory() has side effects, such as opening a connection, that is a real bug.
The lock here also covers the call to factory(). That keeps the logic simple, but it blocks every other thread that wants the cache while a slow factory runs. See the next section for that trade-off.
Choosing lock granularity
How much data one lock covers is the lock's granularity.
| Approach | Benefit | Cost |
|---|---|---|
| One coarse lock for a whole structure | Simple, hard to get wrong | Threads queue up, so you lose the parallelism you moved to free-threading for |
| Many fine locks, such as one per object or per shard | More threads run at once | More code, higher risk of deadlock, and invariants that span objects are harder to keep |
A good rule is to start coarse and measure. Only split a lock when profiling shows threads waiting on it. Keep critical sections short. Do slow work such as I/O, network calls, or heavy computation outside the lock, and hold the lock only to read or write the shared data.
import threading
results = []
results_lock = threading.Lock()
def process(item):
value = item * item # heavy work stays outside the lock
with results_lock: # only the shared write is protected
results.append(value)Deadlock and lock ordering
A deadlock happens when threads wait for each other forever. Thread 1 holds lock X and wants Y. Thread 2 holds Y and wants X. Neither can continue.
The standard fix is a global lock order. Every thread that needs more than one lock takes them in the same order. In this example the order comes from an account ID.
import threading
class Account:
def __init__(self, account_id, balance):
self.account_id = account_id
self.balance = balance
self.lock = threading.Lock()
def transfer(src, dst, amount):
if src is dst:
raise ValueError("cannot transfer to the same account")
first, second = sorted((src, dst), key=lambda a: a.account_id)
with first.lock:
with second.lock:
if src.balance < amount:
raise ValueError("insufficient funds")
src.balance -= amount
dst.balance += amount
a = Account(1, 100)
b = Account(2, 100)
transfer(a, b, 30)
transfer(b, a, 10)
print(a.balance, b.balance) # 80 120Because both transfer(a, b, ...) and transfer(b, a, ...) lock account 1 first, they cannot deadlock each other.
Other habits that help:
- Do not call unknown code, such as callbacks, while holding a lock. That code may try to take another lock.
- Do not hold a lock while waiting on another thread, for example with
thread.join(). - Use a timeout when a stuck thread would be worse than a failed operation.
import threading
lock = threading.Lock()
if lock.acquire(timeout=2.0):
try:
pass # critical section
finally:
lock.release()
else:
print("could not get the lock within 2 seconds")Re-entrant locks
A plain Lock is not re-entrant. If a thread that holds it tries to acquire it again, the thread blocks forever and deadlocks with itself. This happens easily when one locked method calls another locked method on the same object.
threading.RLock lets the owning thread acquire the lock repeatedly. The lock is released for other threads only after the thread has released it as many times as it acquired it.
import threading
class Inventory:
def __init__(self):
self._items = {}
self._lock = threading.RLock()
def add(self, name, qty):
with self._lock:
self._items[name] = self._items.get(name, 0) + qty
def add_many(self, pairs):
with self._lock: # one lock hold for the whole batch
for name, qty in pairs:
self.add(name, qty) # re-acquires the same lock safely
inv = Inventory()
inv.add_many([("bolt", 10), ("nut", 5), ("bolt", 2)])
print(inv._items) # {'bolt': 12, 'nut': 5}RLock is slightly slower than Lock. Prefer a plain Lock and a design where locked methods call private unlocked helpers. Use RLock when that restructuring is not practical.
Other primitives in `threading`
Locks are the building block, but other primitives fit specific jobs.
| Primitive | Use it when |
|---|---|
| `Lock` | Exactly one thread at a time may use a resource |
| `RLock` | The same thread may need to take the lock again |
| `Semaphore` | A limited number of threads, such as 5 connections, may use a resource |
| `Condition` | A thread must wait until some state becomes true, and another thread signals the change |
| `Event` | One thread signals a one-time flag, such as "shutdown" or "ready", to others |
A Condition always wraps a lock. The waiting thread must check its condition in a while loop, because it can wake up when the condition is not yet true.
import threading
items = []
cond = threading.Condition()
def consumer():
with cond:
while not items: # re-check after every wake-up
cond.wait()
print("got", items.pop())
def producer():
with cond:
items.append("job-1")
cond.notify()
c = threading.Thread(target=consumer)
c.start()
threading.Thread(target=producer).start()
c.join()Common mistakes
- Locking only the writers. A reader that skips the lock can see a half-finished update, such as the
balanceof one account changed but not the other. - Different locks for the same data. Two threads that each use their own
Lockobject do not exclude each other. Create the lock once, next to the data it guards, and share it. - Creating the lock inside the function.
with threading.Lock():makes a new lock on every call, and it protects nothing. - Holding the lock across slow work. This keeps the code correct but removes the parallel speedup.
- Assuming a GIL-era test is proof. A race that never appeared on a standard build can fail often on a free-threaded one. Test on the free-threaded interpreter, and run stress tests with many threads and many iterations.
Exercise
This function is called from many threads. It is meant to log each user's first visit only once, but sometimes a user appears twice in the log. What is the bug, and how do you fix it? seen = set() log = [] def visit(user): if user not in seen: seen.add(user) log.append(user)
Show answer
The check (user not in seen) and the action (seen.add plus log.append) are separate steps. Two threads can both pass the check before either adds the user, so both append. Each built-in operation is safe alone, but the sequence is not atomic. Fix it by guarding the whole sequence with one lock shared by all threads: create lock = threading.Lock() once at module level, then write with lock: around the if statement and its body.
Exercise
Two threads call transfer(a, b, 10) and transfer(b, a, 10) on a version of transfer that locks src.lock first and dst.lock second. What can go wrong, and what is the standard fix?
Show answer
Thread 1 can hold a.lock and wait for b.lock, while thread 2 holds b.lock and waits for a.lock. Neither can proceed, which is a deadlock. The standard fix is a global lock order: sort the two accounts by a stable key such as account_id and always acquire the lock of the lower one first, so both threads request the locks in the same order.