Winter Semester 2026–27 · VIT-AP · BACSE106 · Operating Systems · Dr. Krithika L.B

Synchronization hardware

Why software alone is not enough on modern machines.

Module 3 Session 3.3 Lesson 1 of 3

Operating Systems: Synchronization Hardware

Hardware-Supported Primitives for Mutex Locks & Atomic Operations

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:

1. test_and_set() Instruction

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;
}
2. compare_and_swap() (CAS) Instruction

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 calls test_and_set(&lock). It receives false, exits the while loop, and sets lock to true atomically.
  • Lock Held (lock == true): Any subsequent process executing test_and_set(&lock) receives true, staying trapped in the while loop (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().

Process P0

Remainder Section

Process P1

Remainder Section

Process P2

Remainder Section
Hardware Bus Lock State: lock = false | Active Process in CS: None