Course contentsShow
← Computer Science
Lesson 2555 of 2,87257. Concurrency FundamentalsFree lesson

Race Conditions

Understand race conditions: when program correctness depends on the timing of thread execution.

Race Conditions

What you'll learn: You'll understand what race conditions are and why they make concurrent programs behave unpredictably.

The Core Problem

A race condition occurs when the correctness of your program depends on the timing or order in which threads execute. When multiple threads access shared data and at least one modifies it, the final result can vary depending on which thread "wins the race" to execute first.

The dangerous part? The program might work correctly 99 times, then fail catastrophically on the 100th run — simply because the thread scheduling happened differently.

A Real-World Analogy

Imagine two roommates checking the fridge simultaneously. Both see there's one egg left. Both decide to use it for breakfast. Roommate A cracks it into their pan while Roommate B reaches for it — surprise, it's gone! The outcome depended on who acted first, and both made decisions on stale information.

Why Race Conditions Are Subtle

Race conditions are notoriously hard to debug because:

  • Non-deterministic: They don't happen every time
  • Timing-sensitive: More likely under certain loads or on faster/slower hardware
  • Heisenbug nature: Adding debugging code can change timing enough to hide the bug
  • Appear thread-safe superficially: Individual operations may look safe in isolation

Without proper synchronization (which we'll cover in later lessons), any shared mutable state accessed by multiple threads is vulnerable.

Common Scenarios

Race conditions typically emerge when threads perform "check-then-act" sequences on shared data: checking a balance before withdrawing money, reading a counter before incrementing it, or testing if a resource exists before using it.

Key Takeaway: Race conditions occur when program correctness depends on unpredictable thread timing — they're the fundamental reason thread safety requires careful synchronization of shared mutable state.