Sub topic 9
Spinlocks and mutex locks
This chapter assumes you know what a critical section is and the three requirements for a solution: mutual exclusion, progress and bounded waiting. It also assumes you have seen test-and-set and compare-and-swap, and that you understand preemption and context switching. Here we turn the atomic instruction into a usable lock, and we compare a lock that busy-waits (a spinlock) with one that sleeps (a mutex).
From atomic instruction to lock
An atomic instruction such as test-and-set reads and writes a memory word in one indivisible step. A lock is a small protocol built on top of it. Every lock has two operations, acquire and release, and the code between them is the critical section.
#include <stdatomic.h>
atomic_flag lock = ATOMIC_FLAG_INIT;
void acquire(void) {
while (atomic_flag_test_and_set(&lock))
;
}
void release(void) {
atomic_flag_clear(&lock);
}atomic_flag_test_and_set sets the flag and returns its old value. If the old value was 0, the caller found the lock free and now owns it. If the old value was 1, someone else owns it, so the caller loops and tries again. The loop that keeps testing is called busy waiting, and a lock that waits this way is a spinlock.
Checking the three requirements
GATE questions often ask you to verify a lock against the requirements. For the test-and-set spinlock above:
| Requirement | Satisfied? | Reason |
|---|---|---|
| Mutual exclusion | Yes | Only one test-and-set can see the value 0, because the instruction is atomic. |
| Progress | Yes | If the lock is free and processes want it, one of them will get it. A process outside its critical section never blocks others. |
| Bounded waiting | No | Nothing orders the waiters. A process can lose every race while others enter repeatedly. |
Bounded waiting fails because the winner of each race is decided by hardware timing, not by arrival order. A process may spin forever while others keep acquiring and releasing.
A spinlock with bounded waiting
The textbook fix adds a waiting array and passes the lock to the next waiting process in cyclic order. Here the shared variables are waiting[n] (all false) and lock (false). Each process i also has a local variable key.
#include <stdbool.h>
#include <stdatomic.h>
#define N 4
bool waiting[N];
atomic_bool lock_word = false;
void enter(int i) {
waiting[i] = true;
bool key = true;
while (waiting[i] && key)
key = atomic_exchange(&lock_word, true);
waiting[i] = false;
}
void leave(int i) {
int j = (i + 1) % N;
while (j != i && !waiting[j])
j = (j + 1) % N;
if (j == i)
atomic_store(&lock_word, false);
else
waiting[j] = false;
}atomic_exchange plays the role of test-and-set here: it stores true and returns the old value. When leaving, process i scans the processes after it in cyclic order. If it finds a waiter j, it sets waiting[j] to false. That frees j from its loop without ever clearing lock_word, so the lock passes directly to j. If nobody is waiting, i clears lock_word. Any waiting process therefore enters within at most n - 1 turns, which gives bounded waiting.
The same idea works with compare-and-swap. compare_and_swap(&lock, 0, 1) sets the lock to 1 only if it is currently 0, and returns the original value. A spinlock built on it loops while the returned value is not 0.
Spinlock costs and when they make sense
A spinning process uses CPU time and does no useful work. This cost shapes where spinlocks belong.
- On a single CPU, spinning is pointless. The lock holder cannot run while the spinner holds the CPU, so the spinner burns its whole time slice until it is preempted.
- On a multiprocessor, spinning is reasonable when the lock is held for less time than a context switch takes. The waiter avoids the cost of sleeping and waking.
- Spinlocks suit very short critical sections, such as updating a counter or a list pointer.
- Operating system kernels use spinlocks inside interrupt handlers, where sleeping is not allowed.
A rule of thumb: if the expected wait is shorter than two context switches (one to sleep, one to wake), spin. Otherwise sleep.
The loop also hurts the memory system. Every test-and-set is a write, so on a multiprocessor each spinning CPU keeps pulling the cache line holding the lock away from the others. A common improvement is test-and-test-and-set: spin on a plain read until the lock looks free, and only then try the atomic instruction. Reads can be served from each CPU's own cache, so there is far less traffic.
Mutex locks
A mutex lock (short for mutual exclusion lock) is a lock whose waiters sleep instead of spinning. It has a boolean available and a queue of blocked processes. The exact implementation differs between systems, but the idea is:
acquire: if the lock is available, take it. Otherwise, put the calling process in the lock's wait queue and block it. The scheduler runs something else.release: if the wait queue is empty, mark the lock available. Otherwise, move one waiter from the queue to the ready queue and hand it the lock.
The caller that finds the lock held pays for a context switch to sleep and another to wake, but it uses no CPU in between. Kernels use short spinlocks to protect the mutex's own queue, so the spinning is moved into a tiny critical section.
Here is the standard POSIX interface.
#include <pthread.h>
#include <stdio.h>
#define ITERATIONS 100000
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static long counter = 0;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < ITERATIONS; i++) {
pthread_mutex_lock(&m);
counter++;
pthread_mutex_unlock(&m);
}
return NULL;
}
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, work, NULL);
pthread_create(&b, NULL, work, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld\n", counter);
return 0;
}Compile with gcc -pthread. The program prints counter = 200000 every time. Without the mutex, the two counter++ operations would interleave as load, add and store, and the result would usually be smaller.
Spinlock versus mutex
| Property | Spinlock | Mutex |
|---|---|---|
| Waiting behaviour | Busy waiting | Sleeps in a wait queue |
| CPU use while waiting | Full | None |
| Cost to acquire when free | Very low | Low |
| Cost to acquire when held | None extra, but wasted cycles | Two context switches |
| Best for | Short critical sections on multiprocessors | Longer critical sections, or a single CPU |
| Usable in interrupt handlers | Yes | No, because they may sleep |
Common errors
- Forgetting to release on every exit path, including early
returnand error branches. The lock then stays held and every other process waits forever. - Releasing a lock you do not own. A mutex normally assumes the holder unlocks it. This is one difference from a binary semaphore, which any process may signal.
- Acquiring a non-recursive lock twice in the same thread. The second acquire waits for a release that can never happen, which is a self-deadlock.
- Holding a spinlock while blocking, for example while waiting for I/O. Other CPUs spin for the whole duration.
- Calling a lock "fair" because it guarantees mutual exclusion. Fairness needs bounded waiting, which plain test-and-set lacks.
Exercises
Exercise
A spinlock uses a plain test-and-set with no ordering. Three processes P1, P2 and P3 repeatedly acquire and release it. P3 never gets the lock in a long run. Which of the three critical-section requirements is violated, and which are not?
Show answer
Bounded waiting is violated, because P3 can be bypassed an unlimited number of times. Mutual exclusion holds because test-and-set is atomic. Progress holds because whenever the lock is free, some waiting process acquires it.
Exercise
In the bounded-waiting spinlock with N = 4, process 1 is leaving. Processes 0 and 3 are waiting and process 2 is not. Which process gets the lock, and does lock_word change?
Show answer
The scan starts at j = 2, which is not waiting, then j = 3, which is waiting. Process 3 gets the lock because waiting[3] is set to false. lock_word stays true, so the lock passes directly without being released.
Exercise
A critical section takes 2 microseconds. A context switch takes 5 microseconds. On a multiprocessor, should a waiter spin or sleep on a mutex, and why?
Show answer
It should spin. Sleeping and waking costs about two context switches, or 10 microseconds, which is more than the expected wait of 2 microseconds.