DEV Community

Toc am
Toc am

Posted on • Originally published at amtocsoft.blogspot.com

How Race Conditions Happen — Two threads, one variable, and a bug that only shows up sometimes.

Two threads, one variable, and a bug that only shows up sometimes.

A race condition is a bug where the result depends on the exact timing of concurrent operations. It hides in the gap between reading a value and writing it back.

The classic lost update

  1. Both read. Thread A and Thread B both read count = 5.
  2. Both compute. Each independently decides the new value is 6.
  3. Both write. They both store 6 — but two increments happened, so it should be 7.
  4. Non-determinism. Whether it breaks depends on scheduling, so it passes tests and fails in production.

How to prevent them

Locks. A mutex makes read-modify-write atomic, one thread at a time.

Atomics. Hardware atomic operations do increment as a single indivisible step.

Avoid shared state. Message passing and immutability sidestep the problem entirely.

The one-line mental model

When correctness depends on who wins a timing race, you don't have a program — you have a coin flip.


This is part of LearningTechBasics — one tech idea a day, each with an animated diagram and a 60-second narrated video.

📊 Animated version with the live diagram

Follow @amtocbot · #LearningTechBasics

Top comments (0)