Lesson · Concurrency Fundamentals
Concurrency Correctness & Deadlocks
105 min readConcurrency Correctness & Deadlocks
Concurrent code can be correct in one schedule and fail in another. Atomicity, locks, deadlock, starvation, and graceful shutdown are design concerns that must be reasoned about explicitly.
Learning goals
- Explain atomicity as a property relative to a concurrency model, not something a single line of Python guarantees.
- Define a critical section and protect the whole invariant it covers rather than one variable at a time.
- Describe how a wait-for cycle produces a deadlock and how one documented lock order removes it.
- Tell deadlock, starvation and a missed notification apart by the observation that identifies each.
- Plan a graceful shutdown that stops new work, signals the workers, and waits or cancels by an explicit policy.
Mental model
Races and deadlocks are different failures with different fixes: a race needs a bigger critical section around a whole invariant, while a deadlock needs the lock graph to stay acyclic, usually enforced by one documented acquisition order. Liveness adds a third concern, because a program can be correct and deadlock-free in principle and still never let one worker proceed.
A race needs a bigger critical section, a deadlock a bounded wait
half-finished state on the left, a closed wait-for cycle on the right
Mental model
the same mechanism as a compact list
shared state + interleaving half-finished states become visible ↓ protect the whole invariant one critical section per invariant waiting on more than one lock each worker holds something a peer needs ↓ the wait-for cycle closes deadlock: nobody can make progress break the cycle one global lock order, less nesting
Core idea
Concurrent correctness is about schedules, and the units only make the problem visible: an operation is atomic only relative to the model watching it, which is why one innocent line such as counter += 1 can lose updates once two threads interleave. Two disciplines keep a program honest: define each invariant and protect it as one critical section, and keep the wait-for graph acyclic so ownership can never cycle. Liveness is the closing check, because a program can be race-free and deadlock-free in principle and still starve someone in practice.
Atomicity
An operation is atomic relative to a concurrency model if other participants cannot observe it half-completed. Do not infer atomicity from a single line of Python source.
Critical sections
In Concurrency Correctness & Deadlocks, Critical sections names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Thread safety
In Concurrency Correctness & Deadlocks, Thread safety names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Data races
In Concurrency Correctness & Deadlocks, Data races names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Race conditions
A race condition occurs when correctness depends on the relative timing of concurrent operations. Protect invariants rather than assuming a particular thread or task schedule.
Lock ownership
In Concurrency Correctness & Deadlocks, Lock ownership names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Lock ordering
A global lock-order rule prevents cycles by requiring every code path to acquire multiple locks in the same order. Document the order when more than one lock protects related state.
Deadlocks
A deadlock occurs when participants wait in a cycle that can never make progress. Consistent lock ordering and minimizing nested lock ownership are common prevention techniques.
Starvation
Starvation occurs when a worker remains ready but repeatedly fails to obtain the resources or scheduling opportunity needed to progress. Fairness is a separate property from deadlock freedom.
Liveness
Liveness asks whether useful progress eventually occurs. A program can be race-free yet still fail liveness through deadlock, starvation, or missed notifications.
Thread-local state
Thread-local state is the information that persists between operations in Concurrency Correctness & Deadlocks. Make ownership explicit so you can predict whether two operations observe the same state or independent copies.
Graceful shutdown
Graceful shutdown stops new work, signals existing workers, waits or cancels according to policy, and releases resources. Design it from the beginning instead of treating process exit as cleanup.
Walkthrough
firstandsecondare module-levelLockobjects, andacquire_bothnests them aswith first: with second:, which is exactly the consistent global order the comment prescribes.- The comment above the function shows the deadlock-prone shape: one worker takes
firstthensecondwhile another takessecondthenfirst, so each can hold what the other needs and neither can proceed. - The function returns
"safe lock order"only after both acquisitions succeed, so the nesting does double duty: it enforces the order and it releases both locks on the way out. - Predict before running: what
acquire_both()prints, and what the reversed nesting (with second: with first:) would change about safety if a second worker used it.
Experiments to try
- Reproduce the lost update: ten threads each run
counter += 1a hundred times without a lock, print the final count, and explain the missing increments. - Repair the same script with one
Lockaround the increment, rerun it several times, and note that the total stops varying. - Build the two-lock cycle: one thread acquires
firstthensecond, another acquiressecondthenfirst, and make the standoff visible withacquire(timeout=0.5)instead of blocking forever; then fix it with one order. - Use the playable lab to step through a schedule that loses an update and one that deadlocks, predicting each state before choosing the next transition.
Playable lesson
Lab: Race and deadlock scheduler
Let the learner choose the next worker step. Include a lost-update race and a two-lock wait cycle, then repair both designs.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Race and deadlock scheduler
worker A
not started
counter += 1
local = ?
worker B
not started
counter += 1
local = ?
Shared counter
0
Locks
- free
- free
Blocked
0
of 2 workers
no lock held
Predict first
Two workers each add 1 to a shared counter that starts at 0. What should the final value be?
Both workers run the same line, `counter += 1`, from a starting value of 0. The line only looks like one operation; underneath it is a read, an addition and a write.
Common mistakes
- Protecting individual variables instead of the whole invariant: a lock around one field still lets a reader observe the state between two related updates.
- Acquiring multiple locks in different orders on different code paths: two workers can each hold what the other needs, and the wait-for graph closes into a cycle.
- Treating a timeout as a fix for deadlock:
acquire(timeout=...)lets one thread escape, but the invariant can still be half-updated, so the bug becomes probabilistic instead of gone. - Writing shutdown logic that leaves workers blocked: a worker waiting on a lock or signal nobody will provide keeps the program alive, so shutdown needs a wake-up path, not only a
join().
Practice: Easy
- Run the unlocked counter experiment and record three different totals from three runs; explain the missing increments with the lost-update idea.
- Swap the nesting in
acquire_bothand describe the interleaving that would deadlock if another worker kept the original order. - Call
acquire(timeout=1)on a lock another thread holds and explain what theFalsereturn tells you about that worker's state.
Practice: Medium
- Convert an invariant pair (a balance and its transaction list) so one critical section covers both updates, and describe the bug class that disappears.
- Write two threads that each hold one of two locks and wait for the other with timeouts; record which acquisitions fail, then repair the program with a documented global lock order.
- Extend the counter with a shutdown path: a
threading.Eventthat workers check each iteration, ajoin()with a timeout, and a decision about what happens when a worker is still busy.
Practice: Hard
- Design a locking plan for a small cache: name the invariant, the critical sections, the lock granularity and the documented acquisition order; justify why one lock is enough or why two are needed.
- Build a failure lab with three concurrency failures (a lost update, a deadlock, starvation from an unfair retry loop) and record the single observation that distinguishes each from the other two.
- Stress a graceful shutdown design: start workers, stop intake, signal shutdown, and prove with a bounded script that no worker is left blocked and no new work starts after the signal.
Lesson checklist
- I can explain why a single line like
counter += 1is not atomic across threads. - I can define an invariant and draw its critical section so the whole update is protected.
- I can spot a possible wait-for cycle and name the acquisition order that removes it.
- I can tell deadlock, starvation and a missed notification apart by their observations.
Remember
Correctness under concurrency is a property of schedules, so the work is to rule out the bad ones: protect whole invariants in one critical section, keep the lock graph acyclic with a documented order, and treat liveness (progress for everyone) as a separate obligation from safety. Shutdown belongs to the same design pass, because workers that cannot be woken keep a program from ever finishing.
Interview angles
What is the main purpose of **Atomicity**?+
An operation is atomic relative to a concurrency model if other participants cannot observe it half-completed. Do not infer atomicity from a single line of Python source.
What should you pay attention to when using **Critical sections**?+
In Concurrency Correctness & Deadlocks, Critical sections names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
How does **Thread safety** fit into this lesson?+
In Concurrency Correctness & Deadlocks, Thread safety names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Why is one documented global lock order the standard fix for deadlock, and what helps when no single order is available?+
A wait-for cycle needs at least two acquisition orders to exist, so making every path acquire locks in one order keeps the graph acyclic; when that cannot be imposed, reduce nesting to one lock, or use timeouts and retry so a worker gives up instead of waiting forever.