Sub topic 9
Spinlocks and Mutex Locks
Prerequisites and the locking problem
This chapter assumes you know process and thread basics, C-like pseudocode, and how preemption can interrupt a running thread. A critical section is code that accesses shared data and must not run concurrently with another conflicting critical section.
A lock gives a thread exclusive access to that section:
acquire(lock)
critical section
release(lock)The acquire operation must be atomic. If two threads read “unlocked” at the same time and then both write “locked,” both could enter.
Spinlocks
A spinlock is a lock whose acquire operation repeatedly checks the lock until it becomes free. The thread stays runnable and uses CPU time while waiting.
A common implementation uses atomic test-and-set. Test-and-set reads the old value and sets the lock in one indivisible hardware-supported operation.
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
enum { THREADS = 4, INCREMENTS = 100000 };
atomic_flag spin = ATOMIC_FLAG_INIT;
long counter = 0;
void acquire_spinlock(void) {
while (atomic_flag_test_and_set_explicit(
&spin, memory_order_acquire)) {
/* Busy-wait. */
}
}
void release_spinlock(void) {
atomic_flag_clear_explicit(&spin, memory_order_release);
}
void *worker(void *argument) {
(void)argument;
for (int i = 0; i < INCREMENTS; i++) {
acquire_spinlock();
counter++;
release_spinlock();
}
return NULL;
}
int main(void) {
pthread_t threads[THREADS];
for (int i = 0; i < THREADS; i++)
pthread_create(&threads[i], NULL, worker, NULL);
for (int i = 0; i < THREADS; i++)
pthread_join(threads[i], NULL);
printf("counter = %ld\n", counter);
return 0;
}Compile on a POSIX system with:
cc -std=c11 -pthread spin.c -o spinThe acquire operation uses memory ordering so that reads and writes inside the critical section are not incorrectly moved across the lock operations by the compiler or processor.
A spinlock is useful when the critical section is very short and the lock holder is likely to run immediately. It is inefficient when the wait lasts long. A preempted lock holder is especially dangerous: the waiting thread may consume an entire CPU while the holder is not running.
Mutex locks
A mutex, short for mutual-exclusion lock, normally blocks a waiting thread. The operating system can remove the thread from the running queue and wake it when the mutex becomes available. This avoids wasting CPU cycles.
| Property | Spinlock | Mutex |
|---|---|---|
| Waiting method | Repeatedly checks | Usually sleeps or blocks |
| Best case | Very short critical section | Longer or unpredictable wait |
| Main cost | Wasted CPU time | Blocking and wake-up overhead |
| Typical use | Kernel or low-level code | Application threads |
A mutex does not automatically make all code safe. Every access to the protected data must use the same mutex, and the mutex must be released on every path after successful acquisition.
Neither lock type automatically guarantees fairness. A thread may repeatedly lose the race to acquire the lock. Therefore, bounded waiting depends on the implementation and scheduling policy. Both locks can also contribute to priority inversion, where a high-priority thread waits for a lock held by a low-priority thread. Priority inheritance can reduce this problem in mutex implementations.
Choosing and tracing a lock
Use this decision process:
- Is the protected operation short and nonblocking?
- Could the lock holder be descheduled?
- Is wasting CPU time acceptable?
- Does the implementation provide fairness or priority inheritance?
For an exam question, check whether the lock operation is atomic, whether the critical section is protected, and whether the waiting behavior satisfies the stated requirement. Mutual exclusion alone does not prove progress or bounded waiting.
Exercise
A thread holds a lock while it is preempted for 10 milliseconds. Which lock usually avoids wasting CPU on the waiting thread: a spinlock or a mutex? Why?
Show answer
A mutex usually avoids wasting CPU because the waiting thread can block. A spinlock keeps checking the lock and consumes CPU while the holder is not running.