Test-and-Set and Spinlocks
Software locks like Peterson's break on modern CPUs. Hardware fixes it with one indivisible read-and-write, and a spinlock is the simplest lock you can build from it.
One Indivisible Read and Write
- Read the current value of the lock word.
- Write 1 to the lock word, whatever it held.
- Return the value that was read.
- All three happen atomically – no other processor can read or write the word in between.
A lock needs a thread to check that the lock is free and claim it, with nothing slipping in between. In plain code that is two operations, a read and then a write, and two CPUs can both read 0 before either writes 1. Both then enter the critical section. Software fixes such as Peterson's solution avoid this with careful ordering, but modern processors and compilers reorder memory operations, so those algorithms are not reliable on real hardware without memory barriers.
The hardware answer is an atomic instruction: one instruction that reads and writes a memory word as a single indivisible step. The test-and-set instruction (TAS) is the simplest. It returns the old value of a boolean word and sets the word to true (1), in one operation that no other CPU can interleave with. If two CPUs execute it at the same moment, the hardware serialises them: one reads 0, the other reads 1.
Its behaviour, written as a function, is bool test_and_set(bool *target) { bool old = *target; *target = true; return old; } — except that the whole body executes atomically. On x86 the equivalent is XCHG (or LOCK BTS); C++ exposes it as std::atomic_flag::test_and_set and Java as AtomicBoolean.getAndSet(true).
- Atomic is not the same as fast: a TAS must lock the cache line or the bus, so it costs far more than a plain store
- Calling TAS when the lock is already held changes nothing, since 1 is written over 1
Building a Spinlock
- Acquire –
while (test_and_set(&lock))spins until TAS returns 0. - Critical section – exactly one CPU is here at a time.
- Release –
lock = falselets the next TAS succeed. - Remainder section – the CPU does other work, then may try again.
A spinlock is a lock where a waiting thread keeps retrying in a tight loop instead of going to sleep. With test-and-set it is three lines. Acquire: while (test_and_set(&lock)) ; — keep executing TAS until it returns 0. Critical section. Release: lock = false; — a plain store (with release ordering) is enough, because only the owner ever writes 0.
Why it gives mutual exclusion: the lock word starts at 0. The first TAS to reach it reads 0 and writes 1. Every later TAS reads 1 until the owner stores 0, and the next TAS after that is again the only one to read 0. Because TAS is atomic, two CPUs can never both read 0 for the same release.
The waiting loop is called busy waiting or spinning: the CPU executes instructions the whole time it waits, doing no useful work.
- Pitfall: releasing with a plain non-atomic store and no release ordering lets the compiler or CPU move critical-section writes after the release
- Pitfall: a thread that tries to take a spinlock it already holds spins forever; spinlocks are not re-entrant
Compare-and-Swap and Other Atomic Instructions
Compare-and-swap (CAS) is the more general instruction: compare_and_swap(&value, expected, new) writes new only if the word still equals expected, and returns the old value either way. A spinlock with CAS is while (compare_and_swap(&lock, 0, 1) != 0) ;. CAS is what lock-free data structures are built on, because it can update a word conditionally, for example pushing onto a stack only if the top pointer has not changed since it was read. On x86 it is LOCK CMPXCHG.
Every modern CPU provides at least one such primitive. They differ in how much they can do in one step, but any of them can build a lock.
| Instruction | What it does atomically | Typical use |
|---|---|---|
| Test-and-set | return old value, set word to 1 | simplest spinlock |
| Exchange (swap) | swap a register with a memory word | spinlock (x86 XCHG) |
| Compare-and-swap | write new only if the word equals expected | spinlocks, lock-free stacks and queues |
| Fetch-and-add | add to a word, return the old value | counters, ticket locks |
| Load-linked / store-conditional | store succeeds only if nobody wrote since the load | ARM, RISC-V, POWER equivalent of CAS |
- The ABA problem: CAS only checks the value, so a word that changed from A to B and back to A looks untouched
- LL/SC avoids ABA because any write to the word, even of the same value, makes the store fail
Terms, operations, and practical uses
Core vocabulary
- Atomic instructionA read-modify-write that no other processor can interleave with.
- Test-and-setReturn a word's old value and set it to 1, atomically.
- SpinlockA lock whose waiters loop until it is free instead of sleeping.
- Busy waitingExecuting a loop while waiting; the CPU does no useful work.
- StarvationA waiting thread that loses every race and never gets the lock.
Mechanisms
- TAS spinlockwhile (test_and_set(&lock)) ; … critical section … lock = false;
- CAS spinlockwhile (compare_and_swap(&lock, 0, 1) != 0) ;
- Bounded-waiting TASwaiting[i] = true; spin while waiting[i] && TAS; release hands off to the next waiting[j].
- TTASSpin on a plain read; try TAS only when the lock looks free.
- Ticket lockmy = fetch_and_add(&next, 1); spin until now_serving == my.
Related lessons
- Race Conditions and Critical SectionsThe problem a lock solves, and the three requirements.
- Peterson's SolutionThe software-only lock that hardware atomics replace.
- Mutexes, Semaphores and MonitorsThe sleeping locks built on top of atomic instructions.
- DeadlocksWhat happens when locks are taken in conflicting orders.
Test-and-set: starvation, then bounded waiting
CPUS = ["A", "B", "C"]
# Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
SCHEDULE = "ABCAABCABBACBAABCC"
class Lock:
def __init__(self):
self.word = 0
def test_and_set(self):
# On hardware this read-and-write is one atomic instruction.
old = self.word
self.word = 1
return old
def simulate(bounded):
lock = Lock()
waiting = {c: False for c in CPUS}
phase = {c: "want" for c in CPUS}
fails = {c: 0 for c in CPUS}
entries = []
for t, cpu in enumerate(SCHEDULE, start=1):
if phase[cpu] in ("want", "spin"):
first = phase[cpu] == "want"
if bounded and not first and not waiting[cpu]:
phase[cpu] = "cs"
entries.append((cpu, t))
text = f"waiting[{cpu}] = 0 -> handed the lock, enters"
else:
prefix = ""
if bounded and first:
waiting[cpu] = True
prefix = f"waiting[{cpu}] = 1, "
if lock.test_and_set() == 0:
waiting[cpu] = False
phase[cpu] = "cs"
entries.append((cpu, t))
text = prefix + "TAS read 0 -> acquired"
else:
phase[cpu] = "spin"
fails[cpu] += 1
text = prefix + "TAS read 1 -> spin"
elif phase[cpu] == "cs":
phase[cpu] = "exit"
text = "critical section"
else:
phase[cpu] = "want"
i = CPUS.index(cpu)
later = [CPUS[(i + d) % 3] for d in (1, 2)]
nxt = next((c for c in later if waiting[c]), None)
if bounded and nxt:
waiting[nxt] = False # hand off: the lock word stays 1
text = f"release, hand off to {nxt} (lock stays 1)"
else:
lock.word = 0
text = "release, lock = 0"
print(f"t={t:<2} {cpu}: {text}")
order = " ".join(f"{c}@{t}" for c, t in entries)
print(f"entries: {order}")
print("failed TAS: " + ", ".join(f"{c}={fails[c]}" for c in CPUS))
print("== plain test-and-set spinlock ==")
simulate(False)
print()
print("== bounded-waiting test-and-set ==")
simulate(True)#include <atomic>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
const std::string CPUS = "ABC";
// Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
const std::string SCHEDULE = "ABCAABCABBACBAABCC";
void simulate(bool bounded) {
// A real atomic: exchange(1) is test-and-set (XCHG on x86).
std::atomic<int> lock{0};
std::map<char, bool> waiting{{'A', false}, {'B', false}, {'C', false}};
std::map<char, std::string> phase{{'A', "want"}, {'B', "want"}, {'C', "want"}};
std::map<char, int> fails{{'A', 0}, {'B', 0}, {'C', 0}};
std::vector<std::pair<char, int>> entries;
for (int t = 1; t <= (int)SCHEDULE.size(); t++) {
char cpu = SCHEDULE[t - 1];
std::string text;
if (phase[cpu] == "want" || phase[cpu] == "spin") {
bool first = phase[cpu] == "want";
if (bounded && !first && !waiting[cpu]) {
phase[cpu] = "cs";
entries.push_back({cpu, t});
text = std::string("waiting[") + cpu + "] = 0 -> handed the lock, enters";
} else {
std::string prefix;
if (bounded && first) {
waiting[cpu] = true;
prefix = std::string("waiting[") + cpu + "] = 1, ";
}
if (lock.exchange(1) == 0) {
waiting[cpu] = false;
phase[cpu] = "cs";
entries.push_back({cpu, t});
text = prefix + "TAS read 0 -> acquired";
} else {
phase[cpu] = "spin";
fails[cpu]++;
text = prefix + "TAS read 1 -> spin";
}
}
} else if (phase[cpu] == "cs") {
phase[cpu] = "exit";
text = "critical section";
} else {
phase[cpu] = "want";
int i = CPUS.find(cpu);
char next = 0;
for (int d = 1; d <= 2 && !next; d++) {
if (waiting[CPUS[(i + d) % 3]]) next = CPUS[(i + d) % 3];
}
if (bounded && next) {
waiting[next] = false; // hand off: the lock word stays 1
text = std::string("release, hand off to ") + next + " (lock stays 1)";
} else {
lock.store(0);
text = "release, lock = 0";
}
}
std::string ts = std::to_string(t);
std::cout << "t=" << ts << std::string(3 - ts.size(), ' ') << cpu << ": " << text << "\n";
}
std::cout << "entries:";
for (auto [c, t] : entries) std::cout << " " << c << "@" << t;
std::cout << "\nfailed TAS: A=" << fails['A'] << ", B=" << fails['B'] << ", C=" << fails['C'] << "\n";
}
int main() {
std::cout << "== plain test-and-set spinlock ==\n";
simulate(false);
std::cout << "\n== bounded-waiting test-and-set ==\n";
simulate(true);
}import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class Main {
static final String CPUS = "ABC";
// Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
static final String SCHEDULE = "ABCAABCABBACBAABCC";
static void simulate(boolean bounded) {
// A real atomic: getAndSet(true) is test-and-set.
AtomicBoolean lock = new AtomicBoolean(false);
Map<Character, Boolean> waiting = new HashMap<>();
Map<Character, String> phase = new HashMap<>();
Map<Character, Integer> fails = new HashMap<>();
for (char c : CPUS.toCharArray()) {
waiting.put(c, false);
phase.put(c, "want");
fails.put(c, 0);
}
List<String> entries = new ArrayList<>();
for (int t = 1; t <= SCHEDULE.length(); t++) {
char cpu = SCHEDULE.charAt(t - 1);
String text;
String p = phase.get(cpu);
if (p.equals("want") || p.equals("spin")) {
boolean first = p.equals("want");
if (bounded && !first && !waiting.get(cpu)) {
phase.put(cpu, "cs");
entries.add(cpu + "@" + t);
text = "waiting[" + cpu + "] = 0 -> handed the lock, enters";
} else {
String prefix = "";
if (bounded && first) {
waiting.put(cpu, true);
prefix = "waiting[" + cpu + "] = 1, ";
}
if (!lock.getAndSet(true)) {
waiting.put(cpu, false);
phase.put(cpu, "cs");
entries.add(cpu + "@" + t);
text = prefix + "TAS read 0 -> acquired";
} else {
phase.put(cpu, "spin");
fails.merge(cpu, 1, Integer::sum);
text = prefix + "TAS read 1 -> spin";
}
}
} else if (p.equals("cs")) {
phase.put(cpu, "exit");
text = "critical section";
} else {
phase.put(cpu, "want");
int i = CPUS.indexOf(cpu);
char next = 0;
for (int d = 1; d <= 2 && next == 0; d++) {
char c = CPUS.charAt((i + d) % 3);
if (waiting.get(c)) next = c;
}
if (bounded && next != 0) {
waiting.put(next, false); // hand off: the lock word stays 1
text = "release, hand off to " + next + " (lock stays 1)";
} else {
lock.set(false);
text = "release, lock = 0";
}
}
System.out.printf("t=%-2d %c: %s%n", t, cpu, text);
}
System.out.println("entries: " + String.join(" ", entries));
System.out.printf("failed TAS: A=%d, B=%d, C=%d%n", fails.get('A'), fails.get('B'), fails.get('C'));
}
public static void main(String[] args) {
System.out.println("== plain test-and-set spinlock ==");
simulate(false);
System.out.println();
System.out.println("== bounded-waiting test-and-set ==");
simulate(true);
}
}Step through it
Running on CPUs A, B, C; bus order ABCAABCABBACBAABCC; critical section = 1 tick
Mutual Exclusion, Progress and Bounded Waiting
- Announce –
waiting[i] = true; key = true; - Spin –
while (waiting[i] && key) key = test_and_set(&lock); - Enter –
waiting[i] = false;then run the critical section. - Scan –
j = (i + 1) % n; while (j != i && !waiting[j]) j = (j + 1) % n; - Release or hand off – if
j == isetlock = false, else setwaiting[j] = false.
A correct critical-section solution must satisfy three requirements. The plain TAS spinlock meets the first two but not bounded waiting: when the lock is released, whichever CPU's TAS reaches memory first wins, with no notion of who has waited longest. An unlucky CPU can lose every race indefinitely. That is starvation, and the tracer above shows CPU C failing every attempt while A and B take turns.
The fix keeps a shared array waiting[n], all false. To enter, CPU i sets waiting[i] = true and spins while (waiting[i] && key) key = test_and_set(&lock);. On leaving, it scans j = i+1, i+2, … (mod n) for the first CPU with waiting[j] true. If it finds one it sets waiting[j] = false, handing the lock over directly without ever clearing it. Only if nobody is waiting does it set lock = false. Because the scan moves round the circle, a waiting CPU is served within n − 1 turns.
| Requirement | Plain TAS spinlock | TAS with waiting[] hand-off |
|---|---|---|
| Mutual exclusion | yes – only one TAS reads 0 per release | yes – the lock is either free or handed to exactly one CPU |
| Progress | yes – if the lock is free, some TAS succeeds | yes |
| Bounded waiting | no – a CPU can lose every race | yes – at most n − 1 others enter first |
- The hand-off never sets the lock to 0, so a CPU that arrives late cannot slip in ahead of the one being served
- The scan costs O(n) on every release, which is the price of the n − 1 bound
Busy Waiting, Test-and-Test-and-Set and Ticket Locks
Spinning costs more than the waiting CPU's time. Every TAS is a write, so on a cache-coherent multiprocessor each attempt takes the lock's cache line in exclusive mode and invalidates every other CPU's copy. With several spinners the line bounces between caches and floods the interconnect, slowing down the owner who is trying to finish.
Test-and-test-and-set (TTAS) spins on an ordinary read first: while (true) { while (lock) ; if (!test_and_set(&lock)) break; }. The inner read loop hits in each CPU's own cache and generates no traffic; only when the lock is seen free does a CPU try the expensive TAS. Adding exponential backoff after a failed TAS spreads the retries out further.
A ticket lock fixes fairness with fetch-and-add. Each arriving thread takes my = fetch_and_add(&next_ticket, 1) and spins until now_serving == my; release increments now_serving. Threads enter in exact arrival order, like a deli counter, so waiting is bounded. The Linux kernel used ticket spinlocks from 2.6.25, then moved to queued spinlocks (MCS-style) in which each waiter spins on its own cache line.
| Lock | Spins on | Fair? | Cache traffic while waiting |
|---|---|---|---|
| TAS | atomic write every iteration | no | high – line bounces on every attempt |
| TTAS | plain read, TAS only when free | no | low while held, burst on release |
| TTAS + backoff | read, TAS, then wait longer after failures | no | lower |
| Ticket lock | now_serving counter | yes, FIFO | all waiters reread one line on release |
| MCS / queued lock | a flag in the waiter's own node | yes, FIFO | minimal – one waiter woken per release |
- TTAS still causes a burst on release: every spinner sees 0 at once and all try TAS together
- A ticket lock is fair but has no back-off of its own: if the next ticket holder is preempted, everyone behind it waits
Spinlock vs Mutex
A mutex in the usual OS sense is a sleeping lock: a thread that finds it held is put on a wait queue and blocked, and the CPU runs something else. That costs two context switches, typically microseconds. A spinlock costs nothing to wait except the spinning itself. So the choice depends on how long the wait will be compared with the cost of sleeping and waking.
Spinlocks are the right choice when critical sections are short (a few hundred instructions), when the machine is a multiprocessor so the owner is actually running and will release soon, and in kernel code that cannot sleep, such as interrupt handlers. On a single CPU a spinning thread only wastes its time slice, since the owner cannot run until the spinner is preempted; uniprocessor kernels disable interrupts or preemption instead. Many practical mutexes are hybrids: they spin briefly, then sleep (Linux adaptive mutexes, futex-based locks).
| Aspect | Spinlock | Mutex (sleep lock) |
|---|---|---|
| While waiting | busy-waits on the CPU | blocks; CPU runs other work |
| Cost to wait | CPU cycles for the whole wait | two context switches |
| Best when | critical section is very short | critical section is long or may block |
| Single CPU | wasteful – owner cannot run | fine |
| Interrupt handlers | usable (with interrupts disabled locally) | not allowed – cannot sleep |
| Holder may sleep? | no | yes |
| Examples | Linux spin_lock, std::atomic_flag loops | pthread_mutex_t, Java synchronized when contended |
- Never sleep while holding a spinlock: a waiter would spin for the whole sleep
- In the kernel, take a spinlock with interrupts disabled if an interrupt handler can take the same lock, or the handler spins forever on its own CPU
Strengths, Weaknesses and Uses
Test-and-set is the foundation layer: semaphores, mutexes and monitors are all implemented on top of an atomic instruction, usually guarding their own internal queues with a short spinlock.
Its strengths are simplicity (one instruction and a loop), no context switch to acquire, and use where sleeping is forbidden. Its weaknesses are wasted CPU time while spinning, no bounded waiting without the waiting[] array, heavy cache traffic under contention, and priority inversion when the holder is preempted while others spin.
- OS kernels: run queues, interrupt handlers, per-CPU data
- Building blocks for mutexes, semaphores and condition variables
- Lock-free structures with compare-and-swap
- User-space fast paths in futex-based locks