Two fundamental approaches to preventing race conditions in concurrent systems.
When multiple threads need to modify shared data, we need mechanisms to prevent corruption. Locks use blocking—threads wait in line. CAS is non-blocking—threads retry until they succeed.
In the Lock demo, watch threads queue up and enter one at a time. In the CAS demo, see how threads can fail and retry when their expected value doesn't match.
Only one thread can hold the lock at any time, preventing simultaneous access.
Other threads block and wait until the lock becomes available.
Simple but can cause contention and potential deadlocks if misused.
Assume no conflict, read value, compute new value, then attempt swap.
Hardware ensures compare and swap happen as one uninterruptible operation.
If value changed, re-read and retry. No blocking, just spin.