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

Atomic operations: TAS and CAS

Animated test-and-set and compare-and-swap.

Module 3 Session 3.3 Lesson 2 of 3

Operating Systems: Hardware Synchronization

Atomic Primitives: Test-and-Set & Compare-and-Swap (CAS)

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

1. test_and_set()

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

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 if lock == 0. Since it matches, it atomically sets lock = 1 and returns 0. The process exits the while loop and enters its Critical Section.
  • Lock Held (lock == 1): If another process tries to enter, CAS checks if lock == 0. It fails (since lock == 1), returns 1, and the process remains trapped in the while loop (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.

Process P0

Remainder Section

Process P1

Remainder Section

Process P2

Remainder Section
Shared Hardware Bus State: lock = 0 | Active Process in CS: None