Race Conditions and Mutual Exclusion
When two threads read, change and write the same value, the result depends on timing that nobody controls. A critical section is the stretch that must not be interleaved, and a lock is the usual way to enforce that, at the cost of everything waiting.
What a learner can do afterwards
- Interleave two increment sequences to produce a lost update
- Place a lock around the smallest region that fixes the race
- Explain why a check followed by an action can be wrong even when both are correct
1 · Read
Two threads sharing one value can interleave badly. Each increment reads, changes, and writes back. When both read before either writes, one update is lost.
A balance of 10 gets plus 5 from two threads. Both read 10, both add 5, both write 15. The expected 20 never appears. The lost update leaves 15.
The critical section is the stretch that must not be interleaved: the read, change, and write together. A lock around exactly those lines fixes the race. Everything outside stays unlocked so waiting stays short.
A check followed by an action can fail even when both look correct. Between your check and your act, another thread can change the value. Lock the check together with the act.
Wrap the read-change-write stretch in a lock, including any check it relies on.
2 · Watch
Take it off screen
Where it sits
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.