Skip to main content
CSOS & ConcurrencyDiagramBeginner

Race Condition

KO: 경쟁 조건 (Race Condition)·EN: Race Condition·JA: 競合状態(Race Condition)

A concurrency flaw where program correctness depends on unpredictable execution timing across shared mutable state, causing lost updates or corruption

Table of Contents

Structure Diagram

Race Condition Lost Update in Non-Atomic Read-Modify-Write
Thread A (100 → +50)3 steps
Thread B (100 → +30)3 steps
STEP 1Read 100(25 t)
Quick Answer

What is Race Condition?

A concurrency flaw where program correctness depends on unpredictable execution timing across shared mutable state, causing lost updates or corruption. It is a core concept in OS & Concurrency within CS.

Core Principles

A Race Condition occurs when multiple threads or requests access shared mutable state through non-atomic steps (like read-modify-write), making outcomes depend on unpredictable scheduling order.

  • TOCTOU (Time-of-Check to Time-of-Use): A gap between checking a condition (e.g., balance >= amount) and acting on it allows concurrent requests to double-spend or oversell.
  • Heisenbugs: Adding logs or breakpoints alters timing and hides the bug locally, only for it to surface under production load.

Practical Takeaways

  • Use Atomics (CAS) or Mutexes: Protect counters with hardware Compare-And-Swap atomics and multi-field invariants with locks.
  • Enforce atomicity in the database: Across multiple app servers, use SELECT ... FOR UPDATE (pessimistic locking), version columns (optimistic locking), or atomic conditional updates (WHERE stock >= 1).
  • Run race detectors in CI: Use go test -race, ThreadSanitizer (TSan), or Rust's compile-time borrow checker.

Notable Examples

  • Flash-Sale Overselling: Concurrent checkouts reading the last item in stock simultaneously.
  • Frontend Stale Response Overwrite: An older slow fetch resolving after a newer query (fixed via AbortController).