Locks and synchronization
suggest changeAll threads in a Python process share the same memory. That makes it easy to pass data between them, but it also means two threads can read and modify the same object at the same time and leave it in a broken state. The threading module provides synchronization primitives that coordinate threads:
| Primitive | Use it to |
|---|---|
Lock |
let only one thread at a time run a critical section |
RLock |
same, but the owning thread may acquire it again |
Condition |
wait until some state changes, with notification |
Semaphore, BoundedSemaphore |
allow up to N threads into a section |
Event |
signal a one-time (or resettable) flag to waiting threads |
Barrier |
make N threads wait for each other before continuing |
This article covers each of them, plus deadlocks, check-then-act races, queue.Queue as a lock-free alternative, and the equivalents in asyncio and multiprocessing.
All examples were run with Python 3.13.
Why you need locks: a race condition
The Global Interpreter Lock (GIL) makes sure only one thread runs Python bytecode at a time, but a thread can be switched out between any two bytecodes. A read-modify-write sequence like "read balance, add 1, write balance" is several steps, and another thread can run in the middle:
import threading
import time
balance = 0
def deposit(amount, times):
global balance
for _ in range(times):
current = balance # read
time.sleep(0) # give other threads a chance to run
balance = current + amount # write
threads = [threading.Thread(target=deposit, args=(1, 10_000)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("expected:", 4 * 10_000)
print("actual: ", balance)
expected: 40000
actual: 10150
The exact number changes from run to run. time.sleep(0) just makes the switch very likely so the bug shows up reliably. Without it the bug is still there, it only shows up rarely, which is worse. Even balance += 1 is not atomic: it compiles to separate load, add and store bytecodes.
Don't rely on the GIL for correctness. It's an implementation detail of CPython, and the free-threaded build of Python 3.13+ (python3.13t) removes it entirely. See Global Interpreter Lock for more on the GIL.
Lock
A threading.Lock has two states, locked and unlocked. acquire() blocks until the lock is free and then takes it; release() frees it. Only one thread can hold the lock at a time, so code between acquire() and release() (the critical section) runs in one thread at a time.
Use the lock as a context manager with with. It acquires the lock on entry and always releases it on exit, even if the block raises an exception:
import threading
import time
balance = 0
balance_lock = threading.Lock()
def deposit(amount, times):
global balance
for _ in range(times):
with balance_lock:
current = balance
time.sleep(0)
balance = current + amount
threads = [threading.Thread(target=deposit, args=(1, 10_000)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("expected:", 4 * 10_000)
print("actual: ", balance)
expected: 40000
actual: 40000
The thread switch still happens inside the critical section, but no other thread can enter it until the lock is released, so the read and write can no longer interleave.
Calling acquire() and release() directly is equivalent to with, but you need try/finally to make sure the lock is released if an exception happens:
import threading
lock = threading.Lock()
print(lock.locked())
lock.acquire()
try:
print(lock.locked())
finally:
lock.release()
print(lock.locked())
try:
lock.release()
except RuntimeError as e:
print("RuntimeError:", e)
False
True
False
RuntimeError: release unlocked lock
Prefer with: a lock that is never released because of an exception will hang every other thread that needs it. See Context Managers with Statement.
A Lock is not owned by a thread: any thread may release it, not only the one that acquired it. That is occasionally useful, but usually a sign of a bug.
Non-blocking acquire and timeouts
acquire() takes two optional arguments:
blocking=Falsereturns immediately:Trueif the lock was taken,Falseif it was already heldtimeout=secondswaits at most that long and returnsFalseif the lock wasn't acquired
import threading
import time
lock = threading.Lock()
def hold_lock():
with lock:
time.sleep(0.5)
t = threading.Thread(target=hold_lock)
t.start()
time.sleep(0.1) # make sure the thread grabbed the lock
print("non-blocking:", lock.acquire(blocking=False))
start = time.monotonic()
got_it = lock.acquire(timeout=0.2)
print(f"timeout=0.2: {got_it} after {time.monotonic() - start:.1f}s")
got_it = lock.acquire(timeout=1)
print("timeout=1:", got_it)
if got_it:
lock.release()
t.join()
non-blocking: False
timeout=0.2: False after 0.2s
timeout=1: True
When you acquire manually, only call release() if acquire() returned True. The with statement doesn't support timeouts, so this is the one case where calling acquire() directly is the norm.
Keep critical sections small
While a thread holds a lock, every other thread that needs it is waiting. Hold locks for as short a time as possible and never do slow work (network requests, file I/O, time.sleep()) while holding one unless it's really part of the protected operation. A common pattern is to compute outside the lock and only update shared state inside it:
def process(item):
result = expensive_computation(item) # no lock needed: local data
with results_lock:
results.append(result) # only the shared update is locked
RLock: reentrant lock
A plain Lock doesn't remember who holds it. If the thread holding it tries to acquire it again, it waits for itself forever:
import threading
lock = threading.Lock()
def outer():
with lock:
print("in outer")
inner()
def inner():
# second acquire by the same thread: would block forever
if not lock.acquire(timeout=1):
print("inner: could not acquire, a plain Lock is not reentrant")
return
lock.release()
outer()
in outer
inner: could not acquire, a plain Lock is not reentrant
This happens naturally in classes where public methods take a lock and also call each other. threading.RLock (reentrant lock) solves it: it tracks the owning thread and a recursion count. The owner can acquire it again, and the lock is released only after the same number of release() calls:
import threading
class Account:
def __init__(self, balance=0):
self.balance = balance
self._lock = threading.RLock()
def deposit(self, amount):
with self._lock:
self.balance += amount
def withdraw(self, amount):
with self._lock:
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
def transfer_fee_then_deposit(self, amount, fee):
# holds the lock and calls methods that take it again
with self._lock:
self.withdraw(fee)
self.deposit(amount)
acct = Account(100)
acct.transfer_fee_then_deposit(50, 5)
print(acct.balance)
145
Unlike Lock, an RLock must be released by the thread that acquired it; releasing it from another thread raises RuntimeError. RLock is slightly slower than Lock, so use Lock unless you need reentrancy. An alternative is to have private _deposit_unlocked() helpers that assume the lock is already held.
Condition: wait for state to change
A lock protects data, but sometimes a thread must wait until the data is in a certain state: a queue becomes non-empty, a buffer has free space, a job is finished. Polling in a loop wastes CPU. A threading.Condition lets a thread sleep until another thread notifies it.
A condition is always associated with a lock:
with cond:acquires the underlying lockcond.wait()releases the lock, sleeps until notified, then re-acquires the lock before returningcond.wait_for(predicate)waits untilpredicate()returns truecond.notify(n=1)wakes up tonwaiting threads;cond.notify_all()wakes all of them
Here is a bounded buffer with two conditions sharing one lock. Producers wait while the buffer is full; consumers wait while it is empty:
import threading
from collections import deque
class BoundedBuffer:
def __init__(self, capacity):
self.items = deque()
self.capacity = capacity
lock = threading.Lock()
self.not_empty = threading.Condition(lock)
self.not_full = threading.Condition(lock)
def put(self, item):
with self.not_full:
# always wait in a loop (or use wait_for)
while len(self.items) >= self.capacity:
self.not_full.wait()
self.items.append(item)
self.not_empty.notify()
def get(self):
with self.not_empty:
self.not_empty.wait_for(lambda: len(self.items) > 0)
item = self.items.popleft()
self.not_full.notify()
return item
buf = BoundedBuffer(capacity=2)
results = []
def producer():
for i in range(6):
buf.put(i)
buf.put(None) # sentinel: no more items
def consumer():
while (item := buf.get()) is not None:
results.append(item * item)
threads = [threading.Thread(target=producer), threading.Thread(target=consumer)]
for t in threads:
t.start()
for t in threads:
t.join()
print(results)
[0, 1, 4, 9, 16, 25]
Always re-check the condition after waking up, either with a while loop or with wait_for(). A thread can be woken when the state no longer holds (another thread got there first), and spurious wakeups are allowed. Notify only while holding the lock, and only after changing the state the waiters are checking.
In practice you rarely need to write a bounded buffer: queue.Queue(maxsize=2) is exactly this, implemented with conditions. Conditions are useful when the state you wait on is more complex than "queue has items".
Semaphore: limit concurrency
A threading.Semaphore(n) holds a counter that starts at n. acquire() decrements it, blocking while it's zero; release() increments it. Up to n threads can be inside the protected section at once. It's the standard way to limit access to a resource like a connection pool or the number of simultaneous downloads:
import threading
import time
pool_size = 2
slots = threading.Semaphore(pool_size)
active = 0
max_active = 0
counter_lock = threading.Lock()
def download(n):
global active, max_active
with slots: # at most 2 threads get past this line at once
with counter_lock:
active += 1
max_active = max(max_active, active)
time.sleep(0.1) # pretend to download
with counter_lock:
active -= 1
threads = [threading.Thread(target=download, args=(n,)) for n in range(6)]
start = time.monotonic()
for t in threads:
t.start()
for t in threads:
t.join()
print("max concurrent:", max_active)
print(f"elapsed: {time.monotonic() - start:.1f}s")
max concurrent: 2
elapsed: 0.3s
Six downloads of 0.1s each with two at a time take 0.3s. Note that the semaphore limits concurrency but doesn't protect the shared counters, so they still need their own lock.
A plain Semaphore lets you call release() more times than acquire(), silently raising the limit. BoundedSemaphore raises ValueError instead, which catches that bug:
import threading
s = threading.Semaphore(1)
s.release() # bug: released without acquiring, the count is now 2
print(s.acquire(blocking=False), s.acquire(blocking=False))
b = threading.BoundedSemaphore(1)
try:
b.release()
except ValueError as e:
print("ValueError:", e)
True True
ValueError: Semaphore released too many times
Use BoundedSemaphore for resource limits. Use a plain Semaphore only when it's a counter of available items that legitimately grows.
Event: signal between threads
A threading.Event is a boolean flag. Threads call wait() to block until the flag is set; another thread calls set() to wake all of them. clear() resets it and is_set() checks it without blocking. It's ideal for "startup finished" or "please stop" signals:
import threading
import time
ready = threading.Event()
config = {}
def load_config():
time.sleep(0.2) # slow startup work
config["db"] = "postgres://localhost/app"
ready.set()
def worker(name):
ready.wait() # blocks until set() is called
print(f"{name} using {config['db']}")
workers = [threading.Thread(target=worker, args=(f"w{i}",)) for i in range(3)]
for w in workers:
w.start()
threading.Thread(target=load_config).start()
for w in workers:
w.join()
print("is_set:", ready.is_set())
w0 using postgres://localhost/app
w1 using postgres://localhost/app
w2 using postgres://localhost/app
is_set: True
The order of the worker lines may vary, since all three wake up at once.
wait(timeout) returns True if the event was set and False on timeout. That makes an event a better stop signal than a boolean flag plus time.sleep(): the thread wakes immediately when asked to stop instead of finishing its sleep:
import threading
import time
def ticker(stop):
n = 0
# wait() returns True as soon as the event is set, False on timeout
while not stop.wait(timeout=0.1):
n += 1
print(f"ticker stopped after {n} ticks")
stop = threading.Event()
t = threading.Thread(target=ticker, args=(stop,))
t.start()
time.sleep(0.35)
stop.set()
t.join()
ticker stopped after 3 ticks
See also Stoppable Thread with a while Loop.
Barrier: wait for each other
A threading.Barrier(n) blocks each thread that calls wait() until n threads have called it; then all are released together. Use it for phased algorithms where every thread must finish step 1 before any starts step 2:
import threading
import random
import time
barrier = threading.Barrier(3)
lock = threading.Lock()
log = []
def worker(name):
time.sleep(random.random() / 10)
with lock:
log.append(f"{name} phase 1 done")
idx = barrier.wait() # nobody continues until all 3 arrive
with lock:
log.append(f"{name} phase 2 started")
if idx == 0:
print("exactly one thread gets index 0")
threads = [threading.Thread(target=worker, args=(n,)) for n in "ABC"]
for t in threads:
t.start()
for t in threads:
t.join()
phase1 = [i for i, line in enumerate(log) if "phase 1" in line]
phase2 = [i for i, line in enumerate(log) if "phase 2" in line]
print("all phase 1 before phase 2:", max(phase1) < min(phase2))
exactly one thread gets index 0
all phase 1 before phase 2: True
wait() returns a different index (0 to n-1) to each thread, which is handy for picking one thread to do follow-up work. A barrier can also take an action callable that runs once when the barrier trips, and a timeout. If a wait times out or abort() is called, the barrier is broken and waiting threads get threading.BrokenBarrierError. The barrier resets automatically, so it can be reused for the next phase.
Deadlocks
A deadlock happens when threads wait for each other forever. The classic case is two threads that acquire the same two locks in opposite order:
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
def task1():
with lock_a:
time.sleep(0.1)
if lock_b.acquire(timeout=1):
lock_b.release()
else:
print("task1: deadlock, could not get lock_b")
def task2():
with lock_b:
time.sleep(0.1)
if lock_a.acquire(timeout=1):
lock_a.release()
else:
print("task2: deadlock, could not get lock_a")
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start(); t2.start()
t1.join(); t2.join()
task1: deadlock, could not get lock_b
task1 holds lock_a and waits for lock_b; task2 holds lock_b and waits for lock_a. With a plain with lock_b: both threads would hang forever. Here the timeout lets one of them give up and release its lock, which then lets the other one finish (which thread gives up first can vary).
Timeouts are a way to detect deadlocks, not to fix them. The fix is to always acquire multiple locks in the same global order. For example, when transferring money between two accounts, lock them in order of a stable key regardless of transfer direction:
import threading
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
self.lock = threading.Lock()
def transfer(src, dst, amount):
# always lock accounts in the same global order (here: by name)
first, second = sorted([src, dst], key=lambda a: a.name)
with first.lock, second.lock:
src.balance -= amount
dst.balance += amount
alice = Account("alice", 1000)
bob = Account("bob", 1000)
def many(src, dst):
for _ in range(10_000):
transfer(src, dst, 1)
t1 = threading.Thread(target=many, args=(alice, bob))
t2 = threading.Thread(target=many, args=(bob, alice))
t1.start(); t2.start()
t1.join(); t2.join()
print(alice.balance, bob.balance, alice.balance + bob.balance)
1000 1000 2000
Other rules that prevent deadlocks:
- hold as few locks as possible, ideally one
- don't call unknown code (callbacks, user-supplied functions) while holding a lock
- don't wait for a thread to finish (
join()) while holding a lock that thread needs - use
RLockif the same thread may re-enter a locked section
Check-then-act races
Individual operations on built-in types like dict[key] = value or list.append() are thread-safe in CPython, but a sequence of operations is not. A common bug is checking a condition and then acting on it, assuming nothing changed in between:
import threading
import time
cache = {}
cache_lock = threading.Lock()
calls = 0
def expensive(key):
global calls
calls += 1
time.sleep(0.05)
return key.upper()
def get_racy(key):
if key not in cache: # check
cache[key] = expensive(key) # act
return cache[key]
threads = [threading.Thread(target=get_racy, args=("x",)) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print("racy calls:", calls)
cache.clear()
calls = 0
def get_safe(key):
with cache_lock:
if key not in cache:
cache[key] = expensive(key)
return cache[key]
threads = [threading.Thread(target=get_safe, args=("x",)) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print("safe calls:", calls)
racy calls: 5
safe calls: 1
All five threads saw an empty cache before any of them stored a value, so the expensive function ran five times. Putting both the check and the act inside the same lock makes them one atomic step. The same applies to "if the list is not empty, pop" and "if the file doesn't exist, create it".
Use a queue instead of locks
Often the simplest way to avoid shared state is not to share it. queue.Queue is thread-safe and handles all the locking internally. Threads hand off work through queues instead of modifying shared structures:
import queue
import threading
tasks = queue.Queue()
results = queue.Queue()
def worker():
while True:
n = tasks.get()
if n is None:
break
results.put((n, n * n))
workers = [threading.Thread(target=worker) for _ in range(3)]
for w in workers:
w.start()
for n in range(8):
tasks.put(n)
for _ in workers:
tasks.put(None) # one sentinel per worker
for w in workers:
w.join()
print(sorted(results.get() for _ in range(results.qsize())))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
For a pool of workers that return results, concurrent.futures.ThreadPoolExecutor goes one step further and manages the threads and queues for you. See queue module, Communicating between threads and Creating a worker pool.
asyncio locks
asyncio tasks run in a single thread, but they still interleave at every await. If a read-modify-write spans an await, you have the same race as with threads. The asyncio module has its own versions of the primitives: asyncio.Lock, Condition, Semaphore, BoundedSemaphore, Event and Barrier. Their waiting methods are coroutines, and you use them with async with:
import asyncio
counter = 0
lock = asyncio.Lock()
async def increment():
global counter
async with lock:
current = counter
await asyncio.sleep(0) # suspension point: other tasks run here
counter = current + 1
async def main():
await asyncio.gather(*(increment() for _ in range(1000)))
print(counter)
asyncio.run(main())
1000
Without the lock this prints 1: all 1000 tasks read 0 before any of them writes. Never use a threading.Lock in async code; blocking on it freezes the entire event loop. And asyncio primitives are not thread-safe, so don't share them between threads. asyncio.Semaphore is especially useful for limiting the number of concurrent network requests. See Synchronization Primitive Event.
multiprocessing locks
Processes don't share memory, so threading locks don't work across them. The multiprocessing module has the same set of primitives (Lock, RLock, Semaphore, Event, Condition, Barrier) implemented with OS-level synchronization. Pass them to the child processes as arguments:
import multiprocessing as mp
def add(total, lock, n):
for _ in range(n):
with lock:
total.value += 1
if __name__ == "__main__":
total = mp.Value("i", 0, lock=False)
lock = mp.Lock()
procs = [mp.Process(target=add, args=(total, lock, 5000)) for _ in range(4)]
for p in procs:
p.start()
for p in procs:
p.join()
print(total.value)
20000
mp.Value and mp.Array create a lock for you by default (lock=True), available via get_lock(). Even then, total.value += 1 is two operations and must be wrapped in with total.get_lock():. See Sharing State Between Processes.
Summary
- Any read-modify-write or check-then-act on shared data must be protected by a lock, GIL or not.
- Use
with lock:so the lock is always released; useacquire(timeout=...)when you need to give up. RLockallows the owning thread to re-acquire;Lockdoes not.Conditionwaits for a state change, always in a loop or withwait_for().BoundedSemaphorelimits how many threads use a resource at once.Eventsignals "ready" or "stop";Barriersynchronizes phases.- Avoid deadlocks by acquiring locks in a consistent order and holding them briefly.
- Prefer
queue.QueueorThreadPoolExecutorover hand-written locking when you can. asyncioandmultiprocessinghave their own matching primitives; don't mix them up.