Skip to content

Race Condition ​

A race condition is a situation where several processes or threads access the same shared resource at the same time, and the result changes depending on which one runs first. When the order of simultaneous access gets tangled, data consistency breaks.

At a Glance ​

  • Analogy: two people use one bank account at the same time. The balance is 10,000 won. A and B check the balance almost simultaneously, and each calculates "10,000 won + my 5,000 won deposit = 15,000 won" and writes it down. Since both deposited 5,000 won, the balance should be 20,000 won, but the ledger only shows 15,000 won. One person's deposit has vanished entirely.
  • The problem is that "read → compute → write" is not a single, one-shot operation. It is split into several steps, and another flow of execution can sneak in between them.
  • The same thing happens in databases, where it is called a Lost Update. You can see it alongside Concurrency Problems and Isolation Levels.

Race Condition in Code ​

Four threads each increase the shared variable balance by 1, 1,000 times. If everything worked correctly, the result would be 4,000.

python
import threading
import time

balance = 0  # shared variable used by several threads

def deposit(times):
    global balance
    for _ in range(times):
        current = balance      # 1) read
        time.sleep(0)          # makes it easy to switch to another thread right here
        balance = current + 1  # 2) compute and write

threads = [threading.Thread(target=deposit, args=(1000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print("Expected: 4000")
print("Actual:", balance)

Here are the results of three actual runs.

text
Expected: 4000
Actual: 1001
Expected: 4000
Actual: 1049
Expected: 4000
Actual: 1037
  • The value is different on every run. The operating system decides when threads switch, so the result being unpredictable is itself the hallmark of a race condition. You may get different numbers when you run it.
  • time.sleep(0) is a device that deliberately widens the gap between "read" and "write" so another thread can cut in. A race condition can still happen without this line, but it shows up so rarely that it is hard to see with your own eyes. This is exactly why real bugs of this kind are hard to find: they only blow up "once in a while."

Here is how a value disappears, step by step.

StepThread AThread Bbalance
1Reads balance (100)100
2(pauses briefly)Reads balance (100)100
3Writes 101101
4Writes 101101

Each thread added once, so the value should be 102. But A overwrote it based on the 100 it had read earlier, and B's work was lost.

Critical Section ​

A critical section is the part of the code where multiple flows of execution touch shared data. In the example above, everything from current = balance to balance = current + 1 is the critical section.

In the figure below, two processes run separately until their paths meet at the red dot (the part that touches shared data). That point is the critical section, and the two must be prevented from entering it at the same time.

Two processes' execution flows passing through the same critical section (red dot)

Image source: Wikimedia Commons (Kartikharia, CC BY-SA 4.0)

To prevent a race condition, only one flow may execute the critical section at a time. This is called the critical section problem, and a correct solution must satisfy all three of the following conditions.

ConditionMeaningAnalogy (a single-stall restroom)
Mutual ExclusionWhile one process is in the critical section, no other process can enterIf someone is inside, nobody else can go in
ProgressIf the critical section is empty and some processes want to enter, the choice of who enters must be made without postponing it foreverThe restroom is empty, but nobody goes in because everyone is just waiting on each other: that must not happen
Bounded WaitingA process that has asked to enter must eventually get in (there is a limit on how many times others can cut ahead)Nobody should be cut in front of forever and never get in

The tools that enforce these conditions are locks and semaphores and mutexes. That article also has a version of the example above fixed with a mutex.

Race Conditions Inside the Operating System ​

Race conditions happen not only in user programs but also inside the operating system kernel. Kernel data (for example, the process list or memory usage status) is a shared resource used by every process. There are three typical cases.

1. When an interrupt occurs during kernel work ​

  • Problem: If an interrupt arrives while the kernel is reading and working on some data in kernel mode, the interrupt-handling code may modify the same data. When interrupt handling finishes and the original work resumes, it overwrites the data with the value it read earlier, and the interrupt's change is lost.
  • Solution: While the kernel is modifying important data, it temporarily disables interrupts so nothing can cut in. Once the work is done, it enables them again.
text
Kernel: read count (10)
        ── interrupt occurs ──▶ interrupt handler: count = 11
Kernel: writes count + 1 = 11     ← interrupt's change is lost (should be 12)

2. When a process that entered kernel mode via a system call is switched out midway ​

  • Problem: Process 1 calls a system call and is modifying data in kernel mode when its time slice ends and the CPU moves to Process 2 (context switching). Process 2 also modifies the same kernel data through a system call. When control returns to Process 1, it overwrites the data with the old value, and Process 2's work is not reflected.
  • Solution: While a process is working in kernel mode, the CPU is not taken away even if its time slice ends; the switch happens when it returns from kernel mode to user mode. A kernel like this is called a non-preemptive kernel. However, this approach can make the system less responsive, so modern kernels such as Linux mostly allow switching even in kernel mode and instead put a lock on each piece of shared data.

3. When multiple processors access kernel data in shared memory ​

  • Problem: With several CPUs, two CPUs can modify the same kernel data at literally the same moment. Disabling interrupts does not work here, because it only stops that one CPU while the other CPUs keep running.
  • Solution: Every time shared data in the kernel is accessed, a lock / unlock is performed on that data. Only the CPU holding the lock can modify the data, and the other CPUs wait until the lock is released.

The Three Cases Summarized ​

SituationWho cuts inSolution
Interrupt during kernel workInterrupt-handling codeDisable interrupts during the work
Context switch while handling a system callAnother processDon't take the CPU away in kernel mode (or use locks)
MultiprocessorAnother CPUlock / unlock for each piece of shared data

Race Conditions and Deadlocks ​

When you use locks to prevent race conditions, you can end up with locks waiting on each other instead: a deadlock. The basic rule for locks is "only where needed, for a short time, and always in the same order."

The figure below shows a typical case. Process 1 holds a lock on Resource 1 and waits for Resource 2, while Process 2 holds a lock on Resource 2 and waits for Resource 1. Both are waiting for the other to release its lock, so neither can ever proceed. If both processes had acquired the locks in the same order (Resource 1 → Resource 2), this would not happen.

A deadlock where two processes each hold one resource and wait for the other's resource

Image source: gyoogle tech interview notes, DeadLock

Summary ​

ConceptSummary for non-CS majors
Race conditionSeveral parties modify the same data at once, the order gets tangled, and the value comes out wrong
CauseAnother flow of execution cuts in between "read → compute → write"
CharacteristicThe result differs on every run, so it is hard to reproduce
Critical sectionThe part of the code that touches shared data. Only one may enter at a time
Three conditionsMutual exclusion, progress, bounded waiting
Race conditions in the kernelCaused by interrupts, context switching, and multiple CPUs
Tools to fix itDisabling interrupts, locks, semaphores, mutexes