Lesson 12: Data Races, Deadlock and Atomics
This lesson digs into three hard-to-debug threats: data race (precise C++ definition), deadlock (two threads waiting for each other), and atomic operations (std::atomic) as a lightweight mutex alternative for simple counters.
data race = two people writing on the same paper simultaneously. deadlock = two people hold what the other needs and wait. atomic = an operation that is indivisible — cannot be interleaved.
- data race
- Per the C++ standard: two threads access the same memory location, at least one writes, and there is no synchronisation between them. Causes undefined behavior.
- undefined behavior
- A situation where the C++ standard does not define what happens — the compiler may generate any code including crashes, wrong values, or occasional correct operation.
- deadlock
- A state where two or more threads each wait for the other to release a mutex, and none can ever proceed.
- atomic
- An operation that executes as an indivisible unit. std::atomic<T> in C++ guarantees that read-modify-write is not interrupted by another thread.
- compare-exchange
- An atomic operation that compares the current value to an expected value; if equal, replaces it with a new value. The foundation of lock-free algorithms.