Course contentsShow
← Computer Science
Lesson 1270 of 2,87230. Process SynchronizationFree lesson

What is a Race Condition?

Understanding how concurrent execution of code can produce unexpected results when multiple threads access shared data.

What is a Race Condition?

You'll learn how concurrent execution can produce unexpected and incorrect results when multiple threads access shared data without proper coordination.


The Core Problem

A race condition occurs when the outcome of a program depends on the unpredictable timing or ordering of multiple threads executing simultaneously. When two or more threads access shared data at the same time, and at least one thread modifies that data, the final result can vary based on who gets there first — hence the term "race."

An Everyday Analogy

Imagine two roommates checking the fridge and seeing only one egg left. Both decide to use it for breakfast. Roommate A grabs the egg while Roommate B is getting a pan. When Roommate B returns to the fridge, the egg is gone — but they already decided to cook it! This scheduling mishap happens because they didn't coordinate their actions.

Why It Happens

In concurrent execution (like we see with threads), the CPU scheduler can interleave thread operations in countless ways. Consider two threads both trying to increment a shared counter from 5 to 7:

  • Thread 1 reads the value (5), adds 1, writes back (6)
  • Thread 2 reads the value (5), adds 1, writes back (6)

If both threads read the old value before either writes, the counter ends up at 6 instead of the correct 7. The threads "raced" to update the same memory location, and the result is wrong.

The Danger

Race conditions create non-deterministic bugs — your program might work perfectly 99 times and fail catastrophically on the 100th run, depending on timing. This makes them extremely difficult to debug.

Key Takeaway: A race condition is an error that occurs when multiple threads access shared data concurrently without synchronization, causing unpredictable and incorrect results based on execution timing.