Article

Optimizing a Spin-Lock

dalvrosa ·Lobsters ·Published 2026-09-10

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…

From the article

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.

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 (); }…


Share this resource


Discovered 2026-09-11 Source Lobsters Archive 2026-09 →