Race Condition: Lost Update
Two 'threads' increment a shared counter, but interleaving causes a lost update. Thread B reads the old value before Thread A finishes writing, so one increment is lost.
A race condition occurs when two threads access shared data without synchronisation and at least one thread writes. The result depends on the exact timing of execution. In the 'lost update' scenario, both threads read the same value, each increments their local copy, then both write back — but the second write overwrites the first, losing one update. This is the most common concurrency bug and leads to incorrect counts, corrupted data, and in security contexts, time-of-check-time-of-use (TOCTOU) vulnerabilities.
Simulator
Walkthrough Guide
- 1
Initialise the shared counter
Do this: Step through the setup: counter at address 128, initial value 0
Watch for: Address 128 = 0. R0 = 128 (counter address)
The shared counter lives at memory address 128. Both threads will read and write this same address. Without synchronisation, the interleaving of their operations determines the final value.
- 2
Thread A loads the counter
Do this: Step through LOAD R1, [R0] (Thread A's load)
Watch for: R1 = 0. Thread A has read the current counter value
Thread A loads the counter (0) into its local register R1. At this point Thread A has not yet written anything back.
- 3
Thread B loads BEFORE A writes back
Do this: Step through LOAD R2, [R0] (Thread B's load)
Watch for: R2 = 0. Thread B reads the same value that A did
This is the critical moment. Thread B reads the counter before Thread A has written its update. Both threads now hold the value 0 in their local registers. They will both compute 0 + 1 = 1.
- 4
Both threads write back the same value
Do this: Step through both ADD and STORE sequences, then LOAD R3, [R0]
Watch for: Thread A stores 1, Thread B stores 1 (overwriting A's write). R3 = 1, not 2
Both threads increment to 1 and write back 1. Thread B's write overwrites Thread A's identical write. The counter shows 1, but two increments were performed — one update was lost. The correct answer should be 2.
Objectives
- •See both Thread A (R1) and Thread B (R2) load the same value 0
- •Watch Thread A store 1, then Thread B overwrites it with 1 again
- •Verify R3 = 1 at the end - one increment was lost
- •Understand that two increments produced only one update due to interleaving
Hints
- The key moment is when Thread B loads the counter before Thread A has written its update back - both threads work with the stale value 0