Class SpinLock

Class Documentation

class SpinLock

High-performance spin lock for very short critical sections (microseconds).

Busy-waits instead of sleeping when contended, making it faster than std::mutex for brief critical sections but wasteful for longer ones. Uses exponential backoff (1-1024 yields) to reduce CPU waste under contention.

Use for: O(1) operations, rare contention, predictable short durations Use std::mutex for: Longer sections, unpredictable duration, high contention

Example:

SpinLock stats_lock;
std::lock_guard lock(stats_lock);
stats.count++;  // Brief critical section

See also

ReentrantSpinLock for reentrant variant

Note

Not reentrant - same thread locking twice deadlocks (use ReentrantSpinLock)

Public Functions

SpinLock() = default
inline bool try_lock()

Attempts to acquire the lock for the current thread without blocking.

Returns:

true if the lock was acquired, false otherwise.

inline void lock()

Blocks until the lock can be acquired for the current thread.

inline void unlock() noexcept

Releases the non-shared lock held by the thread.

The calling thread must have previously acquired the lock.