Sub topic 8
Hardware support: test-and-set and compare-and-swap
This chapter assumes you know the critical-section problem and its three requirements (mutual exclusion, progress, bounded waiting). It also assumes you have seen Peterson's algorithm, and you should be able to read C-like code.
Why software alone is not enough
Peterson's algorithm works only for two processes. It also assumes that memory operations happen in program order. Modern CPUs and compilers reorder reads and writes, so the algorithm needs memory barriers to stay correct. Extending it to many processes is clumsy.
Hardware solves this by providing instructions that read and modify a memory word in one atomic step. An atomic operation is indivisible. No other CPU or interrupt can see or interleave with the middle of it. A lock built on such an instruction needs no clever protocol with flags and turns.
On a single CPU, a kernel can simply disable interrupts inside a critical section. That does not work on multiprocessors, because other CPUs keep running. It is also unsafe for user code. Atomic instructions work on both.
Test-and-set
test_and_set (TAS) does three things as one indivisible step:
- It reads the old value of a memory location.
- It writes 1 to that location.
- It returns the old value.
Its behaviour is the following, shown as pseudocode for the hardware effect.
int test_and_set(int *target) {
int old = *target; // all three lines execute atomically
*target = 1;
return old;
}A lock is a shared variable: 0 means free and 1 means held. The caller that gets 0 back has taken the lock. Every other caller gets 1 and keeps trying.
A spinlock with test-and-set
A spinlock makes a waiting thread loop (spin) until the lock is free. The program below is complete and uses C11 atomics. Four threads each increment a shared counter 100000 times.
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
atomic_flag lock = ATOMIC_FLAG_INIT;
long counter = 0;
void acquire(void) {
while (atomic_flag_test_and_set(&lock))
;
}
void release(void) {
atomic_flag_clear(&lock);
}
void *work(void *arg) {
(void)arg;
for (int i = 0; i < 100000; i++) {
acquire();
counter++;
release();
}
return NULL;
}
int main(void) {
pthread_t t[4];
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, work, NULL);
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
printf("%ld\n", counter);
return 0;
}Compile it with gcc -pthread. It prints 400000. Remove the acquire and release calls and the total usually comes out lower, because counter++ is a read-modify-write race.
Checking the three requirements
| Requirement | Plain TAS spinlock | Reason |
|---|---|---|
| Mutual exclusion | Yes | Only one TAS can return 0 while the lock is 1. |
| Progress | Yes | If the lock is free, some spinning thread's next TAS gets 0. Threads outside the critical section never block others. |
| Bounded waiting | No | Nothing orders the spinners. A fast thread can win the lock again and again while another starves. |
GATE questions often ask exactly this: "does the TAS lock satisfy bounded waiting?" The answer is no.
Compare-and-swap
compare_and_swap (CAS) takes a location, an expected value, and a new value. It also executes atomically:
int compare_and_swap(int *value, int expected, int new_value) {
int old = *value; // all three lines execute atomically
if (old == expected)
*value = new_value;
return old;
}The write happens only if the location still holds the value the caller expected. The return value tells the caller whether it succeeded: success means the returned old value equals expected.
A CAS lock works like this. Each caller tries to swap 0 for 1. Only one succeeds.
#include <stdatomic.h>
atomic_int lock = 0;
void acquire(void) {
int expected = 0;
while (!atomic_compare_exchange_strong(&lock, &expected, 1))
expected = 0;
}
void release(void) {
atomic_store(&lock, 0);
}This lock has the same properties as the TAS lock: mutual exclusion and progress, but no bounded waiting.
CAS beyond locks: retry loops
CAS is more general than TAS because the new value can depend on the old one. A lock-free counter reads the value, computes the new one, and retries if another thread changed the value in between.
#include <stdatomic.h>
void increment(atomic_int *p) {
int old = atomic_load(p);
while (!atomic_compare_exchange_weak(p, &old, old + 1))
; // on failure, old now holds the latest value, so just retry
}No thread ever holds a lock here. If one thread is descheduled in the middle of increment, the others still make progress. The weak variant may fail spuriously on some architectures, which is fine inside a retry loop and can be faster.
| Feature | Test-and-set | Compare-and-swap |
|---|---|---|
| Operand values | Always writes 1 | Writes any new value, only if the old value matches |
| Typical use | Simple locks | Locks, lock-free counters, stacks and queues |
| Returns | Old value | Old value (or success flag) |
| Bounded waiting by itself | No | No |
Getting bounded waiting with test-and-set
To add bounded waiting, threads queue up in a waiting array. When a thread leaves, it scans in cyclic order for the next waiting thread and hands the lock directly to it. If none waits, it releases the lock.
#include <stdatomic.h>
#include <stdbool.h>
#define N 4
atomic_bool waiting[N];
atomic_flag lock = ATOMIC_FLAG_INIT;
void enter_region(int i) {
atomic_store(&waiting[i], true);
bool key = true;
while (atomic_load(&waiting[i]) && key)
key = atomic_flag_test_and_set(&lock);
atomic_store(&waiting[i], false);
}
void leave_region(int i) {
int j = (i + 1) % N;
while (j != i && !atomic_load(&waiting[j]))
j = (j + 1) % N;
if (j == i)
atomic_flag_clear(&lock); // nobody waiting: free the lock
else
atomic_store(&waiting[j], false); // hand the lock to thread j
}Thread i leaves its loop in one of two ways. Either its own TAS returns 0 (key becomes false), or a leaving thread sets waiting[i] to false. The cyclic scan means thread i waits at most N − 1 turns, so bounded waiting holds.
Costs and gotchas
- Busy waiting. A spinning thread burns CPU cycles. Spinlocks pay off only when critical sections are very short, shorter than a context switch. On a single CPU, spinning is pointless: the holder cannot run while the spinner uses the CPU.
- Cache traffic. Every TAS writes to the lock's cache line, even when it fails. Many spinners make that line bounce between CPU caches. A common fix is test-and-test-and-set: spin on a plain read until the lock looks free, then try TAS.
- The ABA problem. CAS only checks that the value equals the expected one. If a value changes from A to B and back to A, CAS cannot tell. This matters in lock-free stacks that compare pointers.
- Memory ordering. Acquire needs acquire semantics and release needs release semantics. C11 defaults to the strongest ordering, so the code above is safe.
- Priority inversion. A spinlock holder that is preempted can leave a higher-priority spinner stuck. A later chapter covers this.
Exercise
Two threads run acquire() from the TAS spinlock at the same moment, and the lock is free. Explain why exactly one of them enters the critical section, and name the requirement the plain lock still fails.
Show answer
The hardware serialises the two TAS operations, so one executes first. It reads 0 and sets the flag to 1. The other then reads 1 and keeps spinning. Only the first thread enters, which gives mutual exclusion. The plain lock fails bounded waiting, because a spinning thread can lose every later race for the lock and starve.
Exercise
A CAS lock starts with lock = 0. Threads A and B both execute compare_and_swap(&lock, 0, 1), with A first. What does each call return, and what is lock afterwards?
Show answer
A's call finds 0, matches the expected value, writes 1, and returns 0 (success). B's call finds 1, which does not match 0, so it writes nothing and returns 1 (failure). Afterwards lock is 1, and B must retry until A releases it.