Protect Invariants with Lock and RLock
Core idea
A Lock excludes competing critical sections. Use a with block to release it even when an exception occurs. RLock allows the owning thread to acquire the same lock recursively, but every acquisition needs a matching release. Prefer ordinary Lock unless nested ownership is intentional.
from threading import Thread, Lockbalance = 5accepted = []lock = Lock()def reserve(): global balance with lock: if balance >= 4: balance -= 4 accepted.append(True)workers = [Thread(target=reserve) for _ in range(2)]for t in workers: t.start()for t in workers: t.join()print(balance, len(accepted))Checking and subtracting occur within the same protected region.
Expected output:
1 1Nest an intentional acquisition
from threading import RLocklock = RLock()def read(): with lock: return 7with lock: print(read())print('released')The same thread can enter the inner region; both contexts release their acquisitions.
Expected output:
7releasedCommon mistake
An RLock does not prevent cycles between different locks. Do not hold locks across slow or unknown callbacks when avoidable.
Practice
Add a deposit operation protected by the same lock. Explain why reads of a consistent balance must follow the same policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Locks and reentrant locks
Check your understanding of locks and reentrant locks.
What is printed?
from threading import Lockl=Lock()with l: print(l.acquire(blocking=False))What is printed?
from threading import RLockl=RLock()with l: print(l.acquire(blocking=False)) l.release()Which region must be protected in reserve?
What does with guarantee on ordinary exceptions?