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
–
- Aread
- Bread
- Aadd
- Badd
- Awrite
- 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 61 The thread copies counter from memory into its own register.
register ← counter
2 3 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.