lock0counter0CPU 0 · ACPU 1 · B1while (test_and_set(&lock))2 ; // spin3counter++;4lock = 0; // unlockKERNEL · WAIT QUEUEz z101100+1+1B
Back: shared memory (lock, counter) and two CPUsFront: the lock code and the kernel's wait queueTokens: values swapped with lock; +1 to counter; B going to sleepAt the back, two shared memory words (lock and counter) and two CPUs running threads A and B. In front, the lock code and the kernel's wait queue. A plain flag lets both threads in. Test-and-set swaps a 1 into lock and hands back the old value in one step: A gets 0 and enters, B gets 1 and spins until A stores 0. A mutex sleeps in the kernel instead of spinning.

The problem

  1. 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.

A spinlock at work

Spin or sleep

What happens

;; step 1/11 · shared
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

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. 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.