Atomic operations: TAS and CAS
Animated test-and-set and compare-and-swap.
Operating Systems: Hardware Synchronization
1. Atomic Hardware Synchronization
Hardware-assisted synchronization relies on special CPU-level atomic instructions. An atomic operation executes fully without preemption or interruption.
2. Foundational Atomic Hardware Instructions
Modifies a single boolean flag atomically. Returns original target value and sets target to true.
boolean test_and_set(boolean *target) { boolean rv = *target; *target = true; return rv; }
Operates on an integer or pointer value. Replaces target value with new_value only if target currently equals expected.
int compare_and_swap(int *value, int expected, int new_value) { int temp = *value; if (*value == expected) *value = new_value; return temp; }
3. Protecting Critical Section with Compare-and-Swap (CAS)
Using compare_and_swap(), a lock is represented by an integer variable lock initialized to 0 (unlocked). A value of 1 indicates the lock is currently held.
// Process Pi implementation using compare_and_swap() int lock = 0; // 0 = unlocked, 1 = locked do { while (compare_and_swap(&lock, 0, 1) != 0); /* Critical Section */ lock = 0; /* Remainder Section */ } while (true);
CAS Lock Execution Step-by-Step:
- Lock Available (
lock == 0):compare_and_swap(&lock, 0, 1)checks iflock == 0. Since it matches, it atomically setslock = 1and returns0. The process exits thewhileloop and enters its Critical Section. - Lock Held (
lock == 1): If another process tries to enter, CAS checks iflock == 0. It fails (sincelock == 1), returns1, and the process remains trapped in thewhileloop (Spinlocking). - Exit Section: The process inside CS sets
lock = 0.
4. Interactive Hardware Synchronization Simulator
Select your desired hardware primitive below and observe how processes use atomic hardware signals to enter and exit their Critical Sections.