Race conditions
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
spot a race and a check-then-act bug.
Planned topics
- A race condition: the result depends on thread timing.
count++is read, add, write: three steps, so updates can be lost.- Check-then-act:
if (stock > 0) stock--;can oversell when two threads pass the check. - Races are intermittent; passing tests do not prove safety.
- Shared mutable state is the root; remove sharing or mutation, or guard it.
Draft outline details
Demonstration
if (stock >= qty) { // thread A and B both pass
stock -= qty; // both subtract: oversell
}Check your understanding
Why is count++ unsafe?
Show answer
It is not atomic: read, modify, write can interleave.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.