Sub topic 4
Shared state, race conditions, and locks
This chapter assumes you can start threads with threading.Thread, call start() and join(), and use with statements. It also assumes you know that threads in one process share memory. Here you will see what goes wrong when threads change the same data, and how locks and queues prevent it.
Shared state
Threads in one process see the same global variables, objects, and lists. That makes it easy to pass results around. It also means two threads can change the same object at the same moment.
Shared state is any data that more than one thread can reach, where at least one thread changes it. If every thread only reads the data, nothing goes wrong. If one thread writes while others read or write, you need a plan.
Local variables are not shared. Each call to a function gets its own locals, even when many threads run the same function. Only objects reachable from more than one thread, such as globals, attributes of a shared object, and items in a shared list, are at risk.
What a race condition is
A race condition is a bug where the result depends on how the operations of several threads interleave. The program may be correct most runs and wrong on others.
The most common form is a lost update, which comes from a read-modify-write sequence:
- Thread A reads a value.
- Thread B reads the same value.
- Thread A writes its new value.
- Thread B writes its new value, overwriting A's.
The following program makes the problem easy to see. The time.sleep call stands in for any delay between reading and writing, such as a network call or a slow calculation.
import threading
import time
balance = 100
def withdraw(amount):
global balance
current = balance # read
time.sleep(0.01) # another thread runs here
balance = current - amount # write
threads = [threading.Thread(target=withdraw, args=(30,)) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
print(balance) # expected 40, usually prints 70Both threads read 100, both compute 70, and both write 70. One withdrawal vanished.
The GIL does not make your code safe
A common belief is that the GIL (Global Interpreter Lock) makes thread-shared code safe. It does not. The GIL ensures that the interpreter's own internal structures stay consistent, and that one bytecode instruction at a time runs in one thread. It does not make a sequence of instructions atomic.
An operation is atomic if no other thread can observe it half-finished. A statement like counter += 1 looks like one step, but it compiles to several bytecode instructions: load the current value, add one, and store the result. The interpreter can switch threads between any two of those steps, so two threads can both load the same old value.
You can inspect this with the dis module:
import dis
counter = 0
def increment():
global counter
counter += 1
dis.dis(increment)The output shows separate load, add, and store instructions. The exact names vary between Python versions, but the read and the write are always distinct steps.
Some single operations are safe in practice. For example, list.append and dict[key] = value on built-in types do not corrupt the object. But combinations of them, such as "check if a key exists, then add it", are not atomic. The language reference does not promise most of these guarantees, and free-threaded builds change the details. Treat them as implementation details and use explicit synchronization for anything that matters.
Protecting shared state with a Lock
A threading.Lock is a mutual exclusion lock, or mutex. Only one thread can hold it at a time. Code between acquiring and releasing the lock is a critical section: a region where at most one thread runs.
Use the lock as a context manager so it is always released, even if the code raises an exception:
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) # 400000The result is always 400000. Each increment happens while holding the lock, so no two threads interleave inside it.
Here is the earlier withdrawal bug, fixed. The whole read-modify-write sits inside one critical section:
import threading
import time
balance = 100
lock = threading.Lock()
def withdraw(amount):
global balance
with lock:
current = balance
time.sleep(0.01)
balance = current - amount
threads = [threading.Thread(target=withdraw, args=(30,)) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
print(balance) # 40Rules for using locks well
- Guard every access to a piece of shared data with the same lock, including reads that must see a consistent value. A lock around only the writes does not help if readers skip it.
- Keep critical sections short. Threads waiting for a lock do no work, so a long section turns your program back into a sequential one.
- Do not do slow I/O while holding a lock unless the I/O is part of what must be atomic.
- Keep the lock next to the data it protects, for example as an attribute of the same object, so the pairing is clear.
Lock details you will meet
Lock.acquire() accepts blocking and timeout arguments. lock.acquire(timeout=2) returns False if the lock was not obtained within two seconds. If you call acquire yourself, you must call release in a try/finally block. The with statement does this for you.
A plain Lock is not reentrant. If a thread that already holds it tries to acquire it again, the thread blocks forever. A threading.RLock (reentrant lock) lets the same thread acquire it several times, and it must release it the same number of times. Use an RLock when a locked method calls another locked method on the same object.
| Tool | Same thread can re-acquire | Typical use |
|---|---|---|
| `Lock` | No, it deadlocks | Guarding a short critical section |
| `RLock` | Yes | Methods that call each other under one lock |
| `Semaphore` | Up to a set count of holders | Limiting how many threads use a resource at once |
Deadlock
A deadlock happens when threads wait for each other forever. The classic case uses two locks acquired in opposite order:
- Thread A holds lock 1 and waits for lock 2.
- Thread B holds lock 2 and waits for lock 1.
Neither can proceed. Python does not detect this and the program simply hangs. The usual fixes are:
- Always acquire multiple locks in one fixed global order.
- Use one lock instead of two when the data is closely related.
- Use
acquire(timeout=...)so a thread can give up, log the problem, and back off.
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
def transfer():
# Every thread takes lock_a first, then lock_b.
with lock_a:
with lock_b:
pass # work that needs both resourcesThread-safe queues instead of shared state
Often the best way to handle shared state is to share less of it. queue.Queue is a thread-safe FIFO queue. It does its own locking, so threads can hand work and results to each other without any lock in your code.
import queue
import threading
tasks = queue.Queue()
results = queue.Queue()
STOP = None # sentinel that tells a worker to exit
def worker():
while True:
item = tasks.get()
if item is STOP:
break
results.put(item * item)
threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
t.start()
for n in range(10):
tasks.put(n)
for _ in threads:
tasks.put(STOP) # one sentinel per worker
for t in threads:
t.join()
print(sorted(results.get() for _ in range(10)))Each worker owns its local variables, and the only shared objects are the two queues. The order of the results depends on thread timing, so the program sorts them before printing. Workers that use Queue.get() block until an item is available, which avoids busy-waiting.
For one-way coordination, threading.Event signals "something happened", for example telling workers to stop. Prefer these tools to hand-built flags and polling loops.
Choosing an approach
- Can the threads avoid sharing the data? Give each thread its own copy and combine the results after
join(). This needs no lock. - Is the data passed from producers to consumers? Use a
Queue. - Do several threads update one value or structure in place? Use a
Lockaround every access. - Do locked methods call each other? Use an
RLock.
Exercise
A teammate writes if key not in cache: cache[key] = compute(key) and says it is safe because dict operations are protected by the GIL. Why can this still be wrong with several threads, and how would you fix it?
Show answer
Each single dict operation may be safe, but the check and the assignment are two separate steps. Two threads can both see that the key is missing, and both call compute(key). The result is duplicated work, or two different values if compute is not deterministic. Fix it by holding one lock around the whole check-and-set: with cache_lock: if key not in cache: cache[key] = compute(key). If compute is slow, you can hold the lock only for the check and the store, but then you must accept that two threads may compute the same key at once.
Exercise
Two threads each need locks A and B. Thread 1 does with A: with B: ... and thread 2 does with B: with A: .... What can happen, and what is the simplest change?
Show answer
A deadlock can happen. Thread 1 holds A and waits for B while thread 2 holds B and waits for A, so both wait forever. The simplest change is to make both threads acquire the locks in the same order, for example A first and then B.