Race Condition — Explained with Examples
A race condition occurs when the outcome of concurrent operations depends on the non-deterministic timing of thread execution.
Race conditions arise when multiple threads access shared data without proper synchronization, and the result varies based on execution order. A data race is a specific type where two threads access the same memory location concurrently, at least one writes, and no synchronization is used. Race conditions are notoriously difficult to reproduce and debug because they depend on timing.
Think of a race condition like two people trying to update the same bank account balance simultaneously. Alice checks the balance ($100), then Bob checks ($100). Alice deposits $50 and writes $150. Bob withdraws $20 and writes $80. Bob’s write overwrites Alice’s deposit — the $50 disappears. The account should be $130 but ends up at $80.
Race conditions are prevented through synchronization primitives: mutexes, semaphores, atomic operations, or lock-free data structures.
import threading
# Race condition example
counter = 0
def increment_unsafe():
global counter
for _ in range(100000):
temp = counter
temp += 1
counter = temp # Not atomic — another thread can interleave
# Safe version with mutex
counter = 0
lock = threading.Lock()
def increment_safe():
global counter
for _ in range(100000):
with lock:
counter += 1
# Run unsafe version
threads = [threading.Thread(target=increment_unsafe) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Unsafe result: {counter}") # Probably not 1,000,000
# Run safe version
counter = 0
threads = [threading.Thread(target=increment_safe) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Safe result: {counter}") # Always 1,000,000Functional programming and immutable data structures eliminate entire categories of race conditions by removing shared mutable state.
Mutex, Deadlock, Thread Safety, Critical Section, Lock-Free Programming
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro