Atomic Increment: No Lost Update
The same two-thread counter scenario, but this time each thread completes its full LOAD-ADD-STORE sequence before the other begins. No interleaving means no lost updates.
An atomic operation completes entirely before any other thread can access the same data. When each thread's LOAD-ADD-STORE sequence is atomic (uninterruptible), Thread B always sees Thread A's completed update before starting its own. The result is correct because there is no window for stale reads. In real systems, atomicity is achieved through hardware instructions (e.g. lock cmpxchg), mutexes, or other synchronisation primitives.
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
Same setup as the race condition demo. The difference is entirely in the order of operations.
- 2
Thread A: complete atomic increment
Do this: Step through Thread A's full LOAD / ADD / STORE sequence
Watch for: R1 loads 0, adds 1, stores 1 back to address 128
Thread A completes its entire read-modify-write cycle before Thread B starts. This is what a mutex guarantees: exclusive access to the shared data for the duration of the critical section.
- 3
Thread B: reads the UPDATED value
Do this: Step through Thread B's LOAD / ADD / STORE sequence
Watch for: R2 loads 1 (not 0!), adds 1, stores 2 to address 128
Because Thread A finished first, Thread B reads the updated value (1). It increments to 2 and writes back 2. Both updates are counted correctly.
- 4
Verify the correct result
Do this: Step through LOAD R3, [R0]
Watch for: R3 = 2 — both increments counted
R3 = 2, the correct result. Compare with the race condition demo where R3 = 1. The only difference is ordering: atomic access prevents the stale-read window.
Objectives
- •See Thread A complete its full LOAD-ADD-STORE before Thread B starts
- •Watch Thread B read the updated value 1 (not the stale 0)
- •Verify R3 = 2 at the end - both increments counted
- •Compare with race-condition-demo to see how ordering prevents the bug
Hints
- The only difference from the race condition demo is that Thread A finishes writing before Thread B reads - this is what a mutex or atomic operation guarantees