a spinlock
Picture a single bathroom with no booking system. When you find the door locked, you do not leave — you stand right there and keep jiggling the handle, again and again, until it opens, then you dart in and lock it behind you. You waste your time tugging the handle, but the instant it frees up you are first in. A spinlock is this kind of lock: a thread that wants the lock keeps testing it in a tight loop — spinning — burning CPU cycles until the lock is free, rather than going to sleep.
Under the hood, a spinlock is one shared flag (0 = free, 1 = held) plus an atomic read-modify-write. To acquire, a thread loops trying to atomically flip the flag from 0 to 1 — using test-and-set, or compare-and-swap, or LL/SC. While another thread holds it, every attempt fails and the thread just retries in place. When the holder releases by setting the flag back to 0, one spinning thread's atomic flip finally succeeds and it enters the critical section. A good spinlock spins on a plain read first (a read-only loop that does not generate coherence traffic) and only fires the expensive atomic when the lock looks free — the test-and-test-and-set trick — to avoid hammering the cache line.
Spinlocks are the right tool when the wait is expected to be very short and you have a spare core to spin on — the lock is held only for a few instructions, so spinning a moment is cheaper than the overhead of putting a thread to sleep and waking it. They are the wrong tool for long or contended waits: a spinning thread does zero useful work while burning power and, worse, generating coherence traffic that can slow the very holder it is waiting for. Spinning also risks priority inversion and is disastrous on a single core (you spin out your whole time slice waiting for a holder that cannot run). For longer waits, a blocking mutex that sleeps the thread is better.
Test-and-test-and-set acquire: while (true) { while (lock == 1) ; /* spin read-only until it looks free */ if (CAS(&lock, 0, 1) == success) break; }. Release: lock = 0. The read-only inner spin keeps the cache line Shared and quiet; only the brief CAS attempt fires coherence traffic, and only when the lock appears free.
Spinning on a read-only check first keeps the lock line quiet; the costly atomic fires only when the lock looks free.
Spinlocks suit very short, low-contention critical sections on multicore. For long or heavily contended waits they waste CPU and power and clog coherence traffic; a sleeping mutex is then better, and spinning on a single core can deadlock progress.