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
- 01A spinlock = one atomic flag
- 02T1 lock(): test_and_set -> was clear
- 03T2 lock(): old = true -> spin
- 04T2 spins while T1 works
- 05T1 unlock(): flag.clear() (release)
- 06T2's spin succeeds -> acquires
- 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.