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

Session 3.3: Hardware synchronization (Test-and-Set, Swap) and mutex locks

Atomic instructions that make locks possible on multiprocessors, how to build mutual exclusion and bounded waiting from them, and the mutex lock that programmers actually use.

Module 3 1.5 hours Theory CO3
← Before
3.2 Critical sections
Peterson, Bakery
You are here
3.3 Hardware synchronization (Test-and-Set, Swap) and mutex locks
Module 3 · Process Synchronization
Next →
3.4 Semaphores
wait() and signal()

Learning objectives

By the end of this session you should be able to:

  • Explain why disabling interrupts does not solve the CS problem on multiprocessors.
  • Define test_and_set and Swap/compare_and_swap and build a lock from each.
  • Trace two processes competing for a test_and_set lock.
  • Explain how the waiting[] array adds bounded waiting.
  • Use mutex locks and compare spinlocks with blocking locks.

Lecture notes

1. Why hardware support?

On a uniprocessor the simplest fix is to disable interrupts during the critical section: no timer interrupt → no context switch → no interleaving. This does not work on multiprocessors (other CPUs keep running), disabling interrupts on every CPU is slow, and user programs must not be allowed to do it. Instead, modern CPUs provide special atomic instructions: they read and modify a memory word as one uninterruptible unit, even with several CPUs.

2. test_and_set()

Definition (executed atomically by the hardware) and its use
bool test_and_set(bool *target) {       /* atomic */
    bool rv = *target;                  /* remember old value */
    *target = true;                     /* always set to true */
    return rv;                          /* return old value   */
}

bool lock = false;                      /* shared */

do {
    while (test_and_set(&lock))
        ;                               /* spin while it was already true */
        /* critical section */
    lock = false;
        /* remainder section */
} while (true);
test_and_set lock — two processes race for the lockStep through the interleaving one instruction at a time.

3. Swap / compare_and_swap()

The other classic instruction exchanges two values atomically. The textbook Swap(&a, &b) swaps two words; modern CPUs provide compare-and-swap (CAS, x86 cmpxchg), which writes a new value only if the word still holds an expected value.

Swap-based lock and compare_and_swap
/* Swap version (each process has a local key) */
void Swap(bool *a, bool *b) { bool t = *a; *a = *b; *b = t; }   /* atomic */

do {
    key = true;
    while (key == true)
        Swap(&lock, &key);      /* exits when the old lock value was false */
        /* critical section */
    lock = false;
        /* remainder section */
} while (true);

/* compare_and_swap version */
int compare_and_swap(int *value, int expected, int new_value) {   /* atomic */
    int temp = *value;
    if (*value == expected)
        *value = new_value;
    return temp;
}

while (compare_and_swap(&lock, 0, 1) != 0)
    ;                           /* spin */
    /* critical section */
lock = 0;
These simple locks are not enough on their own

They give mutual exclusion and progress but not bounded waiting — an unlucky process can lose the race forever. A bounded-waiting version uses a waiting[n] array: on exit, a process scans (i+1) … (i−1) and passes the lock directly to the next waiting process, so each waits at most n − 1 turns.

Bounded-waiting mutual exclusion with test_and_set
do {
    waiting[i] = true;
    key = true;
    while (waiting[i] && key)
        key = test_and_set(&lock);
    waiting[i] = false;
        /* critical section */
    j = (i + 1) % n;
    while ((j != i) && !waiting[j])
        j = (j + 1) % n;             /* find next waiting process */
    if (j == i)
        lock = false;                /* nobody waiting: release   */
    else
        waiting[j] = false;          /* hand over directly to Pj  */
        /* remainder section */
} while (true);

Atomic variables (C11 atomic_int, Java AtomicInteger) are built on CAS and make single updates such as count++ safe without a lock.

4. Mutex locks

Hardware instructions are awkward for application programmers, so OS and library designers wrap them in a mutex lock (mutual exclusion). A process must acquire() the lock before entering its critical section and release() it on exit. A boolean available says whether the lock is free; calls to acquire and release must be atomic (implemented with CAS).

Mutex lock
acquire() {
    while (!available)
        ;                 /* busy wait */
    available = false;
}

release() {
    available = true;
}

do {
    acquire();
        /* critical section */
    release();
        /* remainder section */
} while (true);
The same with Pthreads
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_lock(&m);
count++;                       /* critical section */
pthread_mutex_unlock(&m);
Spinlock (busy waiting)

The waiting process loops, wasting CPU. Good on multiprocessors when locks are held for a very short time — no context switch needed. Bad on a single CPU or for long critical sections.

Blocking (sleeping) lock

The waiting process is put to sleep in a queue and woken on release. No wasted cycles, but each wait costs two context switches. Semaphores (Session 3.4) do this.

VideoBytes

Test-and-Set and Swap

Video coming soon

Test-and-Set and Swap

Recorded by Dr. Krithika L.B. Slot m3-tas-swap

Mutex locks and spinlocks

Video coming soon

Mutex locks and spinlocks

Recorded by Dr. Krithika L.B. Slot m3-mutex

Interactive lessons

Work through these in order after the lecture — each one expands a part of the notes with diagrams, hover notes and a quick check.

Lab connection

Check your understanding

Answer each question in your own words first, then reveal the model answer.

Revealed 0
Why must test_and_set be atomic?

If two CPUs could both read false before either wrote true, both would enter the critical section.

Does the simple test_and_set lock satisfy bounded waiting?

No — a process can keep losing the race. The waiting[] array version passes the lock in cyclic order, giving bounded waiting of n − 1.

When is a spinlock preferable to a blocking lock?

On a multiprocessor when the lock is held for less time than two context switches would take.

What does compare_and_swap(&lock, 0, 1) return when the lock is free?

0 (the old value), and it atomically sets lock to 1 — the caller has acquired the lock.

Why is disabling interrupts unsuitable for user programs?

A user program could disable interrupts and never re-enable them, taking over the machine; it also does not stop other CPUs.

Key takeaways

  • Atomic hardware instructions (test_and_set, Swap/CAS) make mutual exclusion possible on multiprocessors.
  • Simple TAS/CAS locks lack bounded waiting; a waiting[] array fixes that.
  • Mutex locks wrap these instructions; spinlocks busy-wait, blocking locks sleep.

Where this leads

A mutex says “one at a time”. What if we need “at most N at a time”, or “B must happen after A”? Semaphores generalise the lock.

Continue to 3.4 — Semaphores →