Advanced · Module 12 · Lesson 1 of 5
Data Races: The Bug Locks Prevent
See why unsynchronized shared increments are undefined behavior, fix the even-odd race with an atomic, and know when a mutex still wins.
By the end you can
- Define a data race and explain why it is undefined behavior
- Replace a racy counter with std::atomic and fetch_add
- Choose between a mutex and an atomic for shared state
Builds on Condition Variables: Waiting for Work.
01 · A question first
Two threads each add a million to the same counter, and the answer comes out 1,999,998. Run it again and it prints a different wrong number. The code has no crash and no exception. What exactly did the hardware do between the load and the store?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- A second runnable example
- Why it is correct
- What it costs
- Pitfalls and variations
- Where it is used
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem