race condition
**Race Condition** — a concurrency bug where the program's behavior depends on the unpredictable timing of thread execution, leading to inconsistent or incorrect results.
**How It Happens**
Two threads access the same shared variable, and at least one writes:
```
Thread A: read counter (=5)
Thread B: read counter (=5)
Thread A: write counter = 5+1 = 6
Thread B: write counter = 5+1 = 6 ← Should be 7!
```
**Types**
- **Data Race**: Unsynchronized concurrent access to shared memory (undefined behavior in C/C++)
- **Race Condition**: Logic error due to timing, even with proper synchronization (e.g., TOCTOU — time-of-check-to-time-of-use)
**Prevention**
- **Mutex/Lock**: Only one thread enters critical section at a time
- **Atomic Operations**: Hardware-guaranteed read-modify-write (e.g., `atomic_fetch_add`)
- **Immutable Data**: If nobody writes, no race possible
- **Thread-Local Storage**: Each thread has its own copy
- **Message Passing**: Communicate by sending messages, not sharing memory
**Detection Tools**
- ThreadSanitizer (TSan) — dynamic detection at runtime
- Helgrind (Valgrind-based)
- Intel Inspector
**Race conditions** are among the most difficult bugs to find — they may only manifest under specific timing conditions that are hard to reproduce.