Python Thread Synchronization: Locks, Semaphores, Events and Queues
This article explains how the threading module coordinates threads that share data, with locks, semaphores, events, conditions and queues, why the classic race condition example rarely fails on CPython, and which errors lead to lost updates and deadlocks.
Threads share the memory of their process, so any of them can read and modify the same objects at any moment, and two threads that update the same value can interleave their steps in a way that loses one of the updates. The present article examines the synchronization primitives of the module threading, which coordinate such access: the lock, the semaphore, the event and the condition, together with the queue, which often replaces them. Each primitive is shown with an example whose result is reproducible, and the article explains why the classic counter example rarely fails on current CPython and why that is no guarantee. Coordinating threads with a handful of small objects, instead of hoping that their steps never collide, is the secret weapon of this module.
Race Conditions and the Lock
A race condition occurs when the result of a program depends on the order in which threads interleave. The classic example increments a shared counter from several threads; on CPython with the global interpreter lock, a loop of counter += 1 gave the correct total in five runs out of five during the tests of this article, because thread switches happen only at certain points of the bytecode. The operation is nevertheless not atomic, and the following example makes the window between reading and writing explicit with time.sleep(0), which invites a switch.
import threading
import time
def run(increment, workers=4, steps=200):
state = {"count": 0}
threads = [threading.Thread(target=increment, args=(state, steps)) for _ in range(workers)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return state["count"]
def unsafe(state, steps):
for _ in range(steps):
current = state["count"]
time.sleep(0) # another thread may run here
state["count"] = current + 1
lock = threading.Lock()
def safe(state, steps):
for _ in range(steps):
with lock:
current = state["count"]
time.sleep(0)
state["count"] = current + 1
print(run(unsafe) < 800) # Output: True
print(run(safe)) # Output: 800
Without the lock, several threads read the same value before any of them writes, and their increments overwrite one another, so the total falls below 800. With the lock, the read and the write form a critical section that only one thread can execute at a time, and the total is exact. The with statement acquires the lock and releases it even if the block raises an exception, the guarantee described in the article devoted to context managers. The distinction matters more since Python 3.14, in which the free-threaded build, without a global interpreter lock, became officially supported (PEP 779): there, threads run truly in parallel and unprotected updates fail far more often, as anticipated in the article devoted to the GIL.
Supply Cap: Limiting Access with a Semaphore
Strategy games impose a supply cap, a maximum number of units that a player may have at once, so that a new unit can be trained only when another one is lost. A semaphore applies the same rule to threads: it holds a counter, each acquire decreases it, each release increases it, and a thread that finds it at zero waits.
import threading
import time
slots = threading.Semaphore(3)
guard = threading.Lock()
active = 0
peak = 0
def download(item):
global active, peak
with slots:
with guard:
active += 1
peak = max(peak, active)
time.sleep(0.05)
with guard:
active -= 1
threads = [threading.Thread(target=download, args=(i,)) for i in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(peak) # Output: 3
bounded = threading.BoundedSemaphore(1)
bounded.acquire()
bounded.release()
try:
bounded.release()
except ValueError as error:
print(type(error).__name__) # Output: ValueError
Eight threads start at once, but no more than three are ever inside the protected block, which is how a program limits simultaneous connections to a server or simultaneous downloads. The counter active is itself protected by a separate lock, since the semaphore admits three threads that would otherwise race on it. A BoundedSemaphore adds a check that an ordinary semaphore lacks: releasing it more times than it was acquired raises ValueError, which reveals a programming error instead of silently raising the limit.
Signals Between Threads: Event
An Event is a flag that threads can wait for: wait blocks until another thread calls set, and then every waiting thread continues at once.
import threading
ready = threading.Event()
started = []
guard = threading.Lock()
def worker(name):
ready.wait()
with guard:
started.append(name)
threads = [threading.Thread(target=worker, args=(name,)) for name in "abc"]
for thread in threads:
thread.start()
print(started) # Output: []
ready.set()
for thread in threads:
thread.join()
print(sorted(started)) # Output: ['a', 'b', 'c']
print(ready.wait(timeout=0.1)) # Output: True
The three workers are blocked until the main thread sets the event, so the list is still empty when it is printed the first time; after set, all of them proceed, in an order that the program does not control, which is why the result is sorted before printing. Once set, the event stays set until clear is called, and wait with a timeout returns whether the flag was set, which makes it suitable for shutdown signals that a loop checks periodically.
Waiting for a State: Condition and Queue
A Condition combines a lock with the ability to wait until some state becomes true: wait releases the lock while sleeping and reacquires it when woken, and wait_for repeats the wait until a predicate holds. For the most frequent case, passing items from producers to consumers, the module queue already provides a complete and thread-safe solution.
import queue
import threading
pot = []
condition = threading.Condition()
served = []
def barista(cups):
for number in range(cups):
with condition:
pot.append(number)
condition.notify()
def customer():
with condition:
condition.wait_for(lambda: pot)
served.append(pot.pop(0))
customers = [threading.Thread(target=customer) for _ in range(3)]
for thread in customers:
thread.start()
barista_thread = threading.Thread(target=barista, args=(3,))
barista_thread.start()
for thread in customers + [barista_thread]:
thread.join()
print(sorted(served)) # Output: [0, 1, 2]
orders = queue.Queue()
results = []
def consumer():
while (item := orders.get()) is not None:
results.append(item * 10)
worker = threading.Thread(target=consumer)
worker.start()
for item in range(3):
orders.put(item)
orders.put(None)
worker.join()
print(results) # Output: [0, 10, 20]
Each customer waits until the pot contains something, and wait_for checks the predicate again after every wake-up, which protects against waking up when another customer has already taken the item. The queue version needs no explicit lock or condition: put and get are synchronized internally, get blocks while the queue is empty, and the value None serves as a signal to stop. The documentation of queue describes it as especially useful when information must be exchanged safely between threads.
Pitfalls of Thread Synchronization
Synchronization errors rarely appear in tests and frequently appear in production, because they depend on timing. Six pitfalls are distinguished, which are the following:
- Trusting lucky results. A race that never fails on one machine may fail on another, under load or on the free-threaded build.
- Deadlock. Two threads that acquire two locks in opposite orders wait for each other forever; a thread that acquires a non-reentrant lock twice blocks itself.
- Forgetting to release. Calling
acquireandreleaseby hand loses the release when an exception occurs;withavoids it. - Waiting without a loop. A thread woken from
Condition.waitmust check its condition again, because the state may have changed;wait_fordoes this automatically. - Primitives across processes. The objects of
threadingcoordinate threads only; processes need their counterparts inmultiprocessing. - Locks that are too wide. Holding a lock during slow work, such as a network call, serializes the threads and removes the benefit of using them.
The second pitfall can be detected with a timeout, as the following example shows.
import threading
lock = threading.Lock()
with lock:
print(lock.acquire(timeout=0.1)) # Output: False
reentrant = threading.RLock()
with reentrant:
print(reentrant.acquire(timeout=0.1)) # Output: True
reentrant.release()
The ordinary lock, already held by the same thread, cannot be acquired again, and without the timeout the program would hang; acquire(timeout=...) returns False instead. A reentrant lock, RLock, can be acquired repeatedly by the thread that holds it, provided that each acquisition is matched by a release.
Choosing a Primitive
Consequently, each coordination problem has a primitive that expresses it directly, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Several threads modify the same data | Lock, with with |
| The same thread may need the lock again | RLock |
| At most N threads may use a resource at once | Semaphore or BoundedSemaphore |
| Threads must wait for a one-time signal | Event |
| Threads wait until a shared state satisfies a condition | Condition with wait_for |
| Producers pass work to consumers | queue.Queue |
| Processes instead of threads | The equivalents in multiprocessing |
The choice between threads, processes and asynchronous code, which precedes the choice of a primitive, is examined in the article devoted to concurrency models.
Conclusion
It is concluded that threads sharing data need explicit coordination, and that the module threading provides it through locks for exclusive access, semaphores for limited access, events for signals and conditions for waiting on a state, while queue.Queue covers the common producer-consumer case without any of them. This magic does not depend on the global interpreter lock, whose protection is incidental and disappears in the free-threaded build of Python 3.14. The opposite strategy, giving each thread or task its own copy of the state so that nothing has to be shared, is the purpose of the module contextvars, developed in a future article of this series.