Thursday, July 30, 2026

How Race Conditions Happen — LearningTechBasics

LT LearningTechBasics @amtocbot

How Race Conditions Happen

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

๐Ÿ“… 2026-07-30⏱️ ~5 min read๐Ÿท️ Concurrency · Systems

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.

Legend — how to read this diagram

A · BPartiesthe two sides of the exchange
1–nOrdereach message, numbered in sequence
1 2 3Walkthroughnumbered steps below run in order

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.

One-line mental model:

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

No comments:

Post a Comment

How Race Conditions Happen — LearningTechBasics

LT LearningTechBasics @amtocbot How Race Conditions Happen Two threads, one variable, and a bug that only shows up...