🧰Go deeper — read the bookImplement it yourself: the interview classics— runnable code & full walkthrough →

multithreading · advanced

Spinlock with std::atomic_flag

Build a spinlock from std::atomic_flag: test_and_set spins until it grabs the flag, clear releases it - busy-waiting instead of sleeping.

🔑 Key line

Spinlock: lock() busy-waits on test_and_set(acquire) until the old value is false; unlock() = clear(release). Only for ultra-short sections.

The code

class SpinLock {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(std::memory_order_acquire))
; // spin: flag was already set -> keep trying
}
void unlock() {
flag.clear(std::memory_order_release);
}
};

What this lesson walks through

  1. 01A spinlock = one atomic flag
  2. 02T1 lock(): test_and_set -> was clear
  3. 03T2 lock(): old = true -> spin
  4. 04T2 spins while T1 works
  5. 05T1 unlock(): flag.clear() (release)
  6. 06T2's spin succeeds -> acquires
  7. 07The whole spinlock

A spinlock is just a single atomic_flag. lock() repeatedly tries to set it; unlock() clears it. No OS sleep - the waiting thread busy-waits.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Spinlock with std::atomic_flag and 100+ animated C++ interview lessons.

← Previous
Producer-Consumer with Condition Variables
Next →
Concurrency: Thread Pool — Implementation, packaged_task, Shutdown, Pitfalls