Synchronization Hardware - aryanjoshi0823/5143-Operating-System GitHub Wiki

Synchronization Hardware: Test-and-Set and Compare-and-Swap

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.


1. Test-and-Set

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.

How It Works

  1. A shared variable, typically called a lock, is initialized to false (indicating no process holds the lock).
  2. 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).

2. Compare-and-Swap (CAS)

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.

  • It atomically:
    1. Compares a memory location's current value with an expected value.
    2. If the two values match, updates the memory location with a new value.
    3. Returns the original value of the memory location.
  • How It Works

    1. The shared variable (e.g., lock) is initialized to a known value.
    2. 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.
    ⚠️ **GitHub.com Fallback** ⚠️