Why: Spinlock#

class Spinlock#

A spinlock for lightweight synchronization with busy-waiting.

The Spinlock class provides a synchronization primitive that uses busy-waiting (spinning) instead of blocking when contention occurs. Unlike traditional mutexes that put waiting threads to sleep, a spinlock causes threads to continuously check (spin) until the lock becomes available.

When to use Spinlocks:

Spinlocks are most efficient when:

  • Critical sections are very short (a few instructions)

  • Lock contention is expected to be low

  • The overhead of context switching would exceed the spin time

  • You need to synchronize in contexts where blocking is not allowed

Caution:

Because spinlocks busy-wait, holding a spinlock for extended periods wastes CPU cycles. On single-core systems, spinlocks can cause performance degradation if the lock holder is preempted while holding the lock, as other threads will spin uselessly until the holder is rescheduled.

This implementation is safe to call from interrupt service routines (ISRs) since it does not interfere with thread scheduling.

Public Functions

Spinlock()#
~Spinlock()#
void lock()#

Spin until an atomic flag can be had

Note that this does not interfere with scheduling, so lock() is safe to call from an ISR.

void unlock()#

Unlock, resetting the flag and resuming a locker/spinner with the flag held.

Spinlock(const Spinlock&) = delete#
Spinlock &operator=(const Spinlock&&) = delete#
Spinlock(Spinlock&&)#
Spinlock &operator=(Spinlock&&)#