</>EmbeddedInterview

What is a spinlock, and what are its advantages and disadvantages?

MediumOperating System Concepts

Short answer: A spinlock is a lock where a waiting thread repeatedly checks ("spins on") the lock variable in a loop instead of sleeping. It is very fast when the lock is held only briefly and the holder is running on another core, because there is no context switch. It wastes CPU time if the wait is long, and it is useless or dangerous on a single core if the holder can be pre-empted.

#include <stdatomic.h>

typedef struct { atomic_flag f; } spinlock_t;
#define SPINLOCK_INIT { ATOMIC_FLAG_INIT }

static inline void spin_lock(spinlock_t *l)
{
    while (atomic_flag_test_and_set_explicit(&l->f, memory_order_acquire))
        ;   /* spin; real implementations add a pause/WFE hint here */
}

static inline void spin_unlock(spinlock_t *l)
{
    atomic_flag_clear_explicit(&l->f, memory_order_release);
}

The acquire/release ordering makes sure memory accesses inside the critical section cannot move outside it.

Advantages

  • No context switch: lowest latency for very short critical sections.
  • Can be used where sleeping is not allowed: interrupt handlers and other atomic contexts in the kernel.
  • Simple, small.

Disadvantages

  • Burns CPU while waiting; with many waiters it wastes a lot of cycles and memory bandwidth (cache-line bouncing).
  • On a single core with pre-emption, a waiter spins for its whole time slice while the holder cannot run. The kernel avoids this by disabling pre-emption while a spinlock is held.
  • If an interrupt handler on the same CPU tries to take a lock that the interrupted code already holds, it deadlocks: use spin_lock_irqsave().
  • Not fair in the simplest form (a waiter can starve); ticket locks and queued spinlocks (MCS/qspinlock) fix fairness and cache traffic.
  • The holder must never sleep.

On ARM: the lock is built from exclusive load/store (LDAXR/STXR) or ARMv8.1 atomics (CAS, SWPA), and waiters use WFE (wait for event) so the core sleeps until the lock line changes, saving power.

Rule of thumb: spinlock if the critical section is shorter than about two context switches and cannot sleep; mutex otherwise. In user space, use a mutex: glibc's pthread_mutex already spins briefly before sleeping (adaptive mutexes), and user-space spinning cannot disable pre-emption.