Course contentsShow
← Computer Science
Lesson 1240 of 2,87228. Operating Systems FundamentalsFree lesson

Threading Challenges: Race Conditions

How concurrent access to shared data by multiple threads can lead to unpredictable results.

Threading Challenges: Race Conditions

You'll learn what happens when multiple threads access shared data simultaneously without proper coordination, leading to unpredictable bugs.


The Problem with Shared Access

A race condition occurs when two or more threads read and write shared data at the same time, and the final result depends on the unpredictable timing of their execution. Because thread scheduling is non-deterministic (the OS decides who runs when), your program can produce different results each time it runs—even with identical inputs.

A Simple Analogy

Imagine two people sharing a single bank account. Both check the balance (100),decidetowithdraw100), decide to withdraw 60, and update the balance. If they do this simultaneously:

  • Person A reads: $100
  • Person B reads: $100
  • Person A withdraws 60,writesback:60, writes back: 40
  • Person B withdraws 60,writesback:60, writes back: 40

The account shows 40,but40, but 120 was withdrawn! One withdrawal "disappeared" because both read the old value before either could update it.

Why It Happens

Consider a simple increment operation on a shared counter:

  1. Thread 1 reads the counter value
  2. Thread 2 reads the same counter value
  3. Thread 1 increments and writes back
  4. Thread 2 increments and writes back (using the old value!)

Instead of two increments, you only got one. The threads "raced" to update the data, and the result is now incorrect.

The Core Issue

Race conditions happen because operations that look atomic (like incrementing a variable) are actually multiple steps at the machine level: read, modify, write. When threads interleave these steps unpredictably, data corruption occurs.

Key Takeaway: Race conditions arise when multiple threads access shared data concurrently without synchronization, causing the program's outcome to depend on unpredictable thread scheduling—a critical bug that requires careful coordination mechanisms to prevent.