Locks, spinlocks and atomic instructions
About this lesson
Two threads on two CPUs both add one to a shared counter. Without care, one update is lost. A lock fixes that, but how do you build a lock when the threads really run at the same moment? Plain loads and stores cannot do it: the check and the set must happen as one step. Follow a spinlock built on the hardware's test-and-set instruction as thread A takes the lock, thread B spins, A updates the counter and lets go, and B gets its turn. Then see why waiting by spinning wastes the CPU, and how a mutex sleeps in the kernel instead. The Software lesson on threads and concurrency shows the race itself; The critical-section problem and Peterson's algorithm sets out the rules a lock must follow.
Two threads, one counter
Two threads run on two CPUs and share one counter. counter++ is really three steps: load, add one, store. If the threads mix those steps, an update can be lost. A lock lets only one thread at a time into that code.
counter++ is three machine steps: load read counter into a register add register + 1 store write the register back thread A runs on CPU 0, thread B on CPU 1, at the same time critical section the code that touches the shared counter lock lets one thread at a time into it
Read the lesson step by step
Two threads, one counter
Two threads run on two CPUs and share one counter. counter++ is really three steps: load, add one, store. If the threads mix those steps, an update can be lost. A lock lets only one thread at a time into that code.
counter++ is three machine steps: load read counter into a register add register + 1 store write the register back thread A runs on CPU 0, thread B on CPU 1, at the same time critical section the code that touches the shared counter lock lets one thread at a time into itA plain flag fails
First try: a flag. Wait while lock is 1, then set it to 1. But both threads can read 0 before either writes 1. Both think the lock is free, both enter, and counter ends at 1 instead of 2.
the broken lock: while (lock == 1) ; lock = 1; A reads lock 0 B reads lock 0 A sets lock 1 B sets lock 1 counter 1 check and set are two separate steps, so the other thread can slip in between them both inside: A and B (no mutual exclusion)One indivisible step
The fix comes from the hardware: an atomic instruction. Test-and-set writes 1 and returns the old value in one indivisible step: no other CPU can touch that memory word in between. On x86-64 this is xchg; C11 calls it atomic_exchange.
test_and_set(&lock), as one step: old = lock lock = 1 return old x86-64 xchg (always locked when it touches memory) RISC-V amoswap C11 atomic_exchange(&lock, 1) <stdatomic.h> another atomic: compare-and-swap (x86: cmpxchg) if lock == expected: lock = new; report the old value start again: lock = 0, counter = 0Thread A takes the lock
Thread A runs test-and-set on lock. It swaps in a 1 and gets back 0. A 0 means the lock was free, so the loop ends and A owns the lock. lock now holds 1.
line 1 while (test_and_set(&lock)) A test_and_set -> 0 swaps in 1, gets back 0: it was free while (0) ends the loop lock = 1 (A owns it)Thread B spins
Thread B runs test-and-set too. It swaps in a 1 and gets back 1: taken. So B loops and tries again, and again. This busy loop is a spinlock, and B's CPU stays busy doing no useful work.
lines 1-2 while (test_and_set(&lock)) ; // spin B test_and_set -> 1 B test_and_set -> 1 ... swaps 1 for 1: nothing changes, the answer says taken B is busy-waiting: running, but making no progressOnly A is inside
Holding the lock, A runs counter++: it loads 0, adds one and stores 1. B cannot get in while lock is 1, so nothing can slip between those three steps. This guarded code is the critical section.
line 3 counter++; A load counter -> 0 A add 0 + 1 = 1 A store counter = 1 B still spinning: every test_and_set returns 1A unlocks
A leaves the critical section and stores 0 in lock. One atomic store is enough to unlock, because only the thread that holds the lock ever does it.
line 4 lock = 0; // unlock lock = 0 on an atomic_int is an atomic store xv6: __atomic_store_n(&lk->locked, 0, __ATOMIC_RELEASE) lock = 0 (free)B gets its turn
B's next test-and-set gets back 0, so now B owns the lock. It loads 1, adds one and stores 2, then unlocks. Two increments and counter is 2: nothing was lost.
B test_and_set -> 0 B counter 1 -> 2 B unlock counter = 2 lock = 0 the whole program (C11 + POSIX threads): #include <pthread.h> #include <stdatomic.h> #include <stdio.h> static atomic_int lock = 0; /* 0 = free, 1 = taken */ static long counter = 0; static int test_and_set(atomic_int *l) { return atomic_exchange(l, 1); /* write 1, return the old value */ } static void *worker(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) { while (test_and_set(&lock)) ; // spin counter++; lock = 0; // unlock } return NULL; } int main(void) { pthread_t a, b; pthread_create(&a, NULL, worker, NULL); pthread_create(&b, NULL, worker, NULL); pthread_join(a, NULL); pthread_join(b, NULL); printf("counter = %ld\n", counter); return 0; } prints: counter = 200000The price of spinning
Back to B waiting. Spinning burns CPU time. On a single CPU it is worse: A cannot even run to unlock until a timer interrupt switches threads. So spinlocks suit short critical sections on several CPUs, which is how kernels use them.
replay: A holds the lock, B spins several CPUs B spins while A works elsewhere: fine if the critical section is short one CPU B spins for its whole time slice; A runs only after the scheduler switches kernels: hold spinlocks "for very short times" (MIT 6.1810)Sleep instead of spin
A mutex waits by sleeping. On Linux, pthread_mutex_lock first tries an atomic instruction. If the lock is taken, a futex system call puts the thread to sleep in the kernel, and the unlock wakes it. No CPU time is burned.
pthread_mutex_lock(&m) (glibc on Linux) free? one atomic instruction, no system call taken? futex wait: sleep in the kernel's queue (only if the word still says taken) pthread_mutex_unlock(&m) waiters? futex wake: the kernel wakes one futex a 32-bit word in user memory the kernel can wait onLocks in one picture
Plain loads and stores cannot build a lock: the check and the set must be one atomic step. Test-and-set gives that step. Spin when the wait is short; sleep in the kernel when it may be long.
the spinlock as a Python simulation: mem = {"lock": 0, "counter": 0} def test_and_set(name): # one indivisible step old = mem[name] mem[name] = 1 return old def thread(me): while test_and_set("lock") == 1: yield me + " spins" yield me + " has the lock" c = mem["counter"] # load yield me + " loaded " + str(c) mem["counter"] = c + 1 # add one, store yield me + " stored " + str(c + 1) mem["lock"] = 0 # unlock yield me + " unlocked" running = [thread("A"), thread("B")] while running: # take turns, one step each for t in list(running): try: print(next(t)) except StopIteration: running.remove(t) print("counter =", mem["counter"]) prints: A has the lock B spins A loaded 0 B spins A stored 1 B spins A unlocked B has the lock B loaded 1 B stored 2 B unlocked counter = 2
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A lock is written as: while (lock == 1) ; lock = 1; Why can two threads both get in?
Between one thread's check and its set, the other thread can do its own check. Both see 0, both set 1, and both enter the critical section.
02What does test-and-set (atomic exchange) do, in one indivisible step?
It returns the old value and leaves 1 behind, with no other CPU able to touch that word in between. Getting back 0 means the lock was free and is now yours; getting back 1 means it was already taken.
03Thread A holds the spinlock. Thread B runs test-and-set on it. What does B get back, and what does it do?
The lock already holds 1, so B swaps 1 for 1: nothing changes and the answer 1 says taken. B keeps looping until A stores 0.
04Why is spinning especially wasteful on a computer with a single CPU?
With one CPU, the spinner holds the only processor. The lock holder makes no progress until a timer interrupt lets the scheduler run it, so the spinner burns its whole time slice for nothing.
05On Linux, what does pthread_mutex_lock usually do when the mutex is already taken?
If an atomic instruction finds the mutex free, no system call is needed. If it is taken, the futex call puts the thread to sleep in a kernel queue, so it uses no CPU while it waits; the unlock wakes it.
Glossary
- Critical section
- A piece of code that uses shared data and must not be run by two threads at the same time.
- Lock (mutex)
- A shared variable that lets only one thread at a time into a critical section. Mutex is short for mutual exclusion.
- Atomic instruction
- An instruction that reads and changes a memory word as one indivisible step: no other CPU can touch that word in between.
- Test-and-set
- An atomic instruction that writes 1 to a word and returns the value that was there before. Also called atomic exchange (xchg on x86-64, amoswap on RISC-V).
- Compare-and-swap
- An atomic instruction that writes a new value only if the word still holds the expected one, and reports what was there (cmpxchg on x86).
- Spinlock
- A lock where a waiting thread loops, trying again and again, until the lock is free. It wastes CPU while it waits.
- Futex
- A Linux mechanism: a 32-bit word in a program's memory that the kernel can put threads to sleep on, and wake them from. Mutexes use it to sleep instead of spin.
Notes and sources
- The card shows the four lines inside worker() that matter. The whole program is real C11 with POSIX threads: two threads each add 1 to counter 100,000 times, and it prints counter = 200,000. Atomics need C11; C99 has no <stdatomic.h>.
- The flag lock fails only when the threads interleave badly, so it can pass many test runs and still be wrong. One bad interleaving is enough.
- On x86-64 the xchg instruction is automatically locked when one operand is in memory, so test-and-set needs no extra prefix there. Compilers turn C11 atomic_exchange into xchg on x86-64 and amoswap on RISC-V.
- Compare-and-swap (cmpxchg on x86) is a stronger atomic: it writes the new value only if the word still holds the expected value. A lock can use it as compare_and_swap(&lock, 0, 1).
- A simple spinlock is not fair: nothing guarantees a spinning thread ever wins, so it can starve. Ticket locks fix this with an atomic fetch-and-add.
- Many mutexes are two-phase: they spin for a short while first, in case the lock is released soon, and only then sleep with a futex.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 28: Locks
- Berkeley CS162, Lecture 8: Lock Implementation, Atomic Instructions, Futex
- MIT 6.1810 (2024), lecture notes: Locking
- xv6 (MIT): kernel/spinlock.c
- cppreference: atomic_exchange (C11)
- x86 instruction reference: XCHG (from the Intel SDM)
- Linux man-pages: futex(7)
- Linux man-pages: futex(2)
- Linux man-pages: pthread_mutex_lock(3p)
- Linux kernel documentation: Lesson 1: Spin locks
Quiz Unlocks after the last step.