Race condition¶
Category: Hazards · Status: stub · Lessons: chapter 02, Shared state
One line: The result depends on the relative timing of tasks, and some timings give a wrong result — whether or not there is also a data race.
Also called: race, interference, general race, resource race.
How it connects¶
flowchart LR
n_aba_problem["ABA problem"]
n_data_race["Data race"]
n_heisenbug["Heisenbug"]
n_interleaving["Interleaving"]
n_mutual_exclusion["Mutual exclusion"]
n_race_condition["Race condition"]
n_safety_failure["Safety failure"]
n_toctou["Time of check to time of use"]
n_aba_problem -->|is a| n_race_condition
n_data_race ---|vs| n_race_condition
n_interleaving -->|can cause| n_race_condition
n_mutual_exclusion -->|prevents| n_race_condition
n_race_condition -->|can cause| n_heisenbug
n_race_condition -->|is a| n_safety_failure
n_toctou -->|is a| n_race_condition
classDef center stroke-width:3px
class n_race_condition center
classDef outside stroke-dasharray: 4 3
class n_aba_problem,n_data_race,n_heisenbug,n_interleaving,n_mutual_exclusion,n_safety_failure,n_toctou outside
- Is a kind of: Safety failure
- Kinds: ABA problem, Time of check to time of use
- Is prevented by: Mutual exclusion
- Can lead to: Heisenbug
- Can be caused by: Interleaving
- Often confused with: Data race
In each language¶
| Rust | The Rustonomicon ↗: Rust prevents data races but not general race conditions, which it calls impossible to prevent when you do not control the scheduler |
| Java | ConcurrentHashMap ↗: putIfAbsent, replace and computeIfAbsent do a check and an update as one atomic action |
Where to read more¶
- In this library: Is total += n safe on two threads?
- In this library: The lost update in a database
- In the books: Grokking Concurrency, Kirill Bobrov — ch. 8, 'Solving concurrency problems: Race conditions and synchronization'
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 3, 'Thread communication using memory sharing' → 'Race conditions'
- In the books: Async Rust, Maxwell Flitton, Caroline Morton — ch. 11, 'Testing' → 'Testing for Race Conditions'
- In the books: Concurrency with Modern C++, Rainer Grimm — ch. 13, 'Challenges' → 'Race Conditions'
- In the books: Parallel Programming and Concurrency with C# 10 and .NET 6, Alvin Ashcraft — ch. 3, 'Best Practices for Managed Threading' → 'Managing deadlocks and race conditions'
- In the books: asyncio Recipes, Mohamed Mustapha Tahrioui — ch. 7, 'Synchronization Between Asyncio Components' → 'Detecting Asyncio Code That Might Have Race Conditions'
- Reference: Wikipedia: Race condition (in software) ↗