Locks
A lock is a mutex that only one thread (or task) may hold at a time. You use it so a read-modify-write on shared state cannot interleave with another.
Detailed Explanation
The GIL does not make balance -= 10 safe. That line is several bytecodes. Two threads can both read 100 and both write 90. threading.Lock fixes that: with lock: balance -= 10. Lock is not reentrant: the same thread acquiring it twice deadlocks. RLock allows that, which is useful when a method takes the lock and calls another method that takes the same lock.
Condition combines a lock with a wait/notify queue: waiters release the lock and sleep until another thread notifys. Event is a sticky flag. Semaphore limits how many holders. Barrier waits until n threads arrive. Prefer the simplest primitive that states the invariant.
Locks are context managers. with lock: acquires and releases even if the block raises. acquire(timeout=...) returns a bool; if you acquire by hand you must release in finally. Releasing a lock you do not hold raises RuntimeError.
Asyncio has asyncio.Lock and friends. They are not thread locks. They only synchronise tasks on the same loop. Mixing threading.Lock into a coroutine can block the loop if the lock is held elsewhere. Mixing asyncio.Lock across threads does not work. Use asyncio.to_thread for blocking work, and keep each lock type in its world.
Hold locks for a short time. Do not do network I/O under a lock unless that I/O is the invariant. Lock ordering prevents deadlock: if every thread acquires A then B, you will not cycle. Document the order.
A queue is often a better design than a shared dict plus a lock. Threads put messages; one owner updates state.
Code Examples
import threading
balance = 100
lock = threading.Lock()
def debit(cents: int) -> None:
global balance
with lock:
if balance < cents:
raise ValueError("insufficient")
balance -= cents
threads = [threading.Thread(target=debit, args=(10,)) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(balance) # 50# Reentrant: same thread may acquire again.
rlock = threading.RLock()
def outer() -> None:
with rlock:
inner()
def inner() -> None:
with rlock:
passCommon Gotchas
Using `Lock` where a method re-enters
deadlock. Use `RLock` or restructure so the lock is taken once at the top.
`asyncio.Lock` vs `threading.Lock`
they do not protect against the other kind of concurrency.
Lock order
A then B in one path, B then A in another, is a deadlock waiting for a schedule.
CPython list `append` is atomic
that does not make a check-then-append sequence atomic. Lock the whole invariant.