⚙️ Python Systems Engineering — 🔒 Locks and Synchronization 🐍
Posted on: November 13, 2026
Description:
Two requests can each perform sensible operations and still break a shared rule. Our fictional reservation system starts with one item: the number of accepted reservations plus remaining stock must stay equal to one.
A correct-looking counter can hide a race
Without synchronization, both workers can read stock = 1, both accept, and both write 0. Stock is not negative, but two reservations were accepted for one item.
The notebook uses a two-party Barrier to force both reads before either write. This makes the failure reproducible; it does not measure how often the race occurs naturally.
Lock the operation, not just the assignment
Wrapping only the write in a lock serializes two decisions based on stale reads. The check and update need to be inside the same critical section:
from threading import Lock
stock = 1
lock = Lock() # One shared lock, created outside the function.
def reserve():
global stock
with lock:
if stock == 0:
return False
stock -= 1
return True
Every competing operation on this state must follow the same locking discipline. A newly created lock per call would not coordinate the workers. Reads that depend on consistent state also need appropriate synchronization.
In the safe notebook case, a start barrier sits before lock acquisition. Putting a two-party barrier inside this critical section would prevent the second worker from entering to release the first.
Actual controlled results
| Version | Accepted | Rejected | Remaining | Rule preserved? |
|---|---|---|---|---|
| Unlocked | 2 | 0 | 0 | No |
| Write-only lock | 2 | 0 | 0 | No |
| Whole-operation lock | 1 | 1 | 0 | Yes |
Each case passed its expected assertions across 25 repetitions on CPython 3.11.9. These are correctness checks, not speed measurements. The animation shows A entering first, but the winning worker is not guaranteed.
Release is not rollback
A lock used as a context manager is released when the block exits, including through an exception. Python does not guarantee which waiting thread acquires it next. See the official threading documentation.
The notebook changes a value to 1, raises an exception, and then successfully reacquires the lock. The value is still 1: releasing the lock does not undo application changes.
Keep the boundary small and explicit
Protect the complete shared-state operation, while keeping unrelated slow work outside it. This example coordinates threads within one process. Multiple server processes or database-backed reservations require coordination at the appropriate shared storage boundary.
Takeaway: protect the rule, share the lock, and distinguish safe release from undoing work.
No comments yet. Be the first to comment!