← Lessons

quiz vs the machine

Gold1450

Concurrency

Race conditions & locks

When two threads read-modify-write the same thing.

5 min read · core · beat Gold to climb

The classic bug

A race condition happens when correctness depends on the timing of two threads. The textbook case: read-modify-write on shared state.

Fixes

  • Mutex / lock — serialize access so only one thread is in the critical section.
  • Atomic operations — compare-and-swap does read-modify-write as one indivisible step.
  • Avoid sharing — give each thread its own state and merge at the end.

Key idea

Locks are correct but cost throughput and risk deadlock (two threads each holding what the other needs). The best concurrency bug is the one you design away by not sharing mutable state.

Practice this →

Check yourself

Answer to earn rating on the learn ladder.

1. Two threads increment a shared counter without synchronization. The bug is…

2. Which performs read-modify-write as one indivisible step?