Concurrency Correctness and Shared State
Protect a shared invariant and reason about failures and cancellation.
python, concurrency, locks, race conditions, cancellation, invariantsProtect a rule, not just a line
Suppose two workers add to a shared count. Reading, calculating, and writing are separate conceptual actions; an unsafe interleaving can lose an update. The invariant here is that the count equals the number of completed increments.
Python illustration
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
count = 0
lock = Lock()
def increment():
global count
with lock:
count += 1
with ThreadPoolExecutor(max_workers=2) as pool:
list(pool.map(lambda _: increment(), range(100)))
print(count)
Prepared output — not live execution:
100
Each worker holds the same lock while changing count; leaving the with
block releases it even on an exception. Consuming the mapped results and
leaving the executor waits for the submitted work. The order of workers is
not specified.
See the reasoning
Coordinate two workers
Explore one possible lock acquisition order, not a guaranteed schedule. This is a prepared demonstration, not live code execution.
Start
- Shared count0Current focus
- Worker Aready
- Worker Bready
Both workers use the same lock; the shared count begins at zero.
Beyond a single lock
A lock only protects participants that follow the same policy. Avoid holding
locks across slow I/O, and use a consistent acquisition order when multiple
locks are necessary to reduce deadlock risk. A thread lock is not an
inter-process lock. Async code generally uses asyncio.Lock for task
coordination rather than blocking the event-loop thread with a thread lock.
For asynchronous tasks, use try/finally for cleanup and normally propagate
CancelledError after cleanup; swallowing it can break structured
concurrency. Timeouts, retries, idempotency, and process failures require
their own design. Tests can exercise chosen schedules but cannot prove that
all possible interleavings are safe.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
