All lessons in Software Engineering: Programs, Systems, and Maintainable Software
Threads, Locks, and Condition Variables
Identify a race, choose a critical section, and wait for a condition correctly.
40 minutes · Members lesson · preview
What you will learn
- Construct an interleaving that violates a shared-state invariant.
- Choose a critical section that protects the complete operation.
- Use a condition predicate and wait loop correctly.
Two threads read available_count as one. Each decides a copy can be allocated, and each writes zero after assigning it to a different member. The final count looks plausible, yet two allocations were made. Looking only at the final counter misses the violated relationship.
Synchronization coordinates access to shared state. Begin with the invariant and the operations that must be observed together. Locking individual reads or writes is not enough when correctness depends on their combination.