Race Conditions
Race Condition: the outcome depends on the timing of interleaved concurrent accesses. For example, two threads increment the same counter without synchronization and lose updates.
Countermeasures: atomic operations, locks, immutable data.
$$\texttt{count++}=\mathrm{load};\,\mathrm{add};\,\mathrm{store}$$
Where used
Any shared counter, cache, or collection without Happens-Before is a production bug under load. Flaky tests are often races.
Depth
A race condition occurs when the result depends on the temporal overlap of competing accesses. Even count++ consists of reading, computing, and writing. Two threads can read the same old value and lose an increment.
Correctness requires that related operations be executed atomically or under an appropriate synchronization rule. It is crucial not only to have mutual exclusion but also visibility: changes made by one thread must be observable to others after synchronization.
Difficulty levels
- Decompose a lost update into single steps.
- Identify critical sections based on shared invariants.
- Justify exclusion and memory visibility together.
Pitfalls
Rare reproduction is not evidence of safety. Logging or debugging can alter timing and mask the error. Also, multiple individually thread-safe methods do not automatically form an atomic overall operation together.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users