A spin-lock is a lock that never sleeps. Instead of yielding to the scheduler, the thread stays on the CPU and spins . No syscalls. No context switches. In this post, we’ll build a version, step by step, that is 5.7x faster while drawing 5.4x less energy.
Benchmark §
Threads increment a shared counter under the lock. 1 1 Run on a box tuned for benchmarking . Built with clang . All optimizations enabled.
template < typename Lockable > auto BM_SpinLock ( benchmark :: State & state ) -> void { alignas ( std :: hardware_destructive_interference_size ) static auto lockable = Lockable {}; alignas ( std :: hardware_destructive_interference_size ) static auto counter = std :: uint64_t {}; pinThread ( state . thread_index ()); for ( auto _ : state ) { lockable . lock (); ++ counter ; lockable . unlock (); } benchmark :: DoNotOptimize ( counter ); }
The lock and the counter get a cache line each. Threads are pinned.
A naive spin-lock §
An atomic bool and an exchange loop.…