Concurrency and Synchronization: Worked Examples
Work through each trace before reading the explanation. Then solve the transfer task without the page open.
Example 1: Two increments can produce one increment
Initially count=0. Thread A reads 0; B reads 0; A writes 1; B writes 1. Both completed an increment, but the final count is 1.
Protect the read-modify-write operation with the same lock, or use an appropriate atomic increment. Locking only the writes still permits both reads to see 0. The critical section is chosen by the invariant, not by which individual statement appears to mutate state.
Example 2: Wakeup is not the predicate
A consumer sees an empty queue and waits. After notification, another consumer can remove the item before this consumer reacquires the lock. Proceeding without checking the queue can therefore fail even without a spurious wakeup.
Wait in a loop while the queue is empty, holding the associated lock when checking and modifying the predicate. The producer updates the queue under that lock and signals according to the API's rules. A notification is an invitation to recheck, not ownership of an item.
Transfer and self-check
A holds lock X then waits for Y; B holds Y then waits for X. Give a prevention rule. Check: a consistent global acquisition order prevents this particular circular wait.
Evidence to keep
Save your first attempt, corrected reasoning, and transfer result as checkpoint evidence. A matching final answer without an explanation is insufficient. Continue with the guided lab and use the reading guide to repair a specific gap.