Skip to content
Optimal Lab

Operating systems · interactive

Race conditions

counter = counter + 1 looks like one step. To the CPU it's three: read, add, write. When two threads do it at once and the scheduler switches between them at the wrong moment, an update disappears.

Thread A

register

–

shared memory

0

counter

Thread B

register

–

  1. Aread
  2. Bread
  3. Aadd
  4. Badd
  5. Awrite
  6. Bwrite

counter = 0. Each thread will add 1, so it should end at 2.

How the scheduler runs them

The scheduler switches threads in the middle. Both read 0.

step 0 of 6
  1. 1

    The thread copies counter from memory into its own register.

    register ← counter

  2. 2

  3. 3

  4. 4

In production

Tools and technologies

Any language with threads has this bug and the same fixes: locks, atomics or not sharing memory.

Not tied to one language — use these names when you search docs or design a system.