The problem
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.
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.
A spinlock at work
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.
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.
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.
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.
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.
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.
Spin or sleep
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.
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.
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.
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.