Synchronization hardware
Why software alone is not enough on modern machines.
Operating Systems: Synchronization Hardware
1. Why Hardware Support is Needed
Software solutions like Peterson's Solution face execution limits on modern multiprocessor computers due to instruction reordering by processors and compilers. To provide efficient synchronization without complex software loops, hardware provides special, atomic CPU instructions.
An Atomic Instruction is an operation that executes as a single, uninterruptible unit of work. If two atomic instructions are executed concurrently on different CPUs, the hardware guarantees they execute sequentially.
2. Special Atomic Hardware Instructions
Modern architectures implement low-level atomic primitives. Two classic foundational instructions are:
Executed atomically. Reads the original value of a boolean variable target, sets target to true, and returns the original value.
boolean test_and_set(boolean *target) { boolean rv = *target; *target = true; return rv; }
Operates on an integer variable. Swaps target to a new_value only if it equals expected, returning the original value.
int compare_and_swap(int *value, int expected, int new_value) { int temp = *value; if (*value == expected) *value = new_value; return temp; }
3. Critical Section Protection with test_and_set()
Using test_and_set(), mutual exclusion can be implemented with a single shared boolean variable lock initialized to false:
// Process Pi implementation using test_and_set() boolean lock = false; do { while (test_and_set(&lock)); // Spinlock (Busy Wait) /* Critical Section */ lock = false; /* Remainder Section */ } while (true);
Execution Logic:
- Lock Free (
lock == false): The first process callstest_and_set(&lock). It receivesfalse, exits thewhileloop, and setslocktotrueatomically. - Lock Held (
lock == true): Any subsequent process executingtest_and_set(&lock)receivestrue, staying trapped in thewhileloop (Spinlock). - Exit Section: The process inside CS sets
lock = false, letting one waiting process claim the lock on its next spin step.
4. Interactive Hardware Spinlock Simulator
Simulate 3 concurrent processes (P0, P1, P2) attempting to claim a hardware-backed lock using test_and_set().