Synchronization Hardware - aryanjoshi0823/5143-Operating-System GitHub Wiki
Synchronization hardware mechanisms like Test-and-Set and Compare-and-Swap provide atomic operations that are essential for implementing mutual exclusion and synchronization in concurrent systems. These mechanisms are implemented directly in the processor to ensure thread-safe access to shared data.
The Test-and-Set instruction is an atomic operation used to test a variable and set it simultaneously. It ensures that no two processes or threads can access the variable at the same time, making it a foundational building block for locks.
- The instruction atomically checks the current value of a memory location and sets it to a new value if it satisfies a condition.
- It returns the original value of the memory location.
- A shared variable, typically called a lock, is initialized to
false
(indicating no process holds the lock). - When a process wants to enter a critical section:
- It invokes
Test-and-Set
on the lock. - If
false
is returned, it means the lock was free, and the process successfully acquires it. - If
true
is returned, another process already holds the lock, so the current process waits (spinlock).
- It invokes
The Compare-and-Swap instruction is another atomic operation used for synchronization. It compares the value of a memory location with a specified value and, if they match, swaps it with a new value.
- Compares a memory location's current value with an expected value.
- If the two values match, updates the memory location with a new value.
- Returns the original value of the memory location.
- The shared variable (e.g.,
lock
) is initialized to a known value. - When a process wants to modify the shared variable, it:
- Compares the current value to the expected value.
- If they match, it updates the variable and continues execution.
- If they don't match, it retries or takes corrective action.