</>EmbeddedInterview

What is the difference between a spinlock and a mutex in the kernel?

MediumLinux Kernel & Device Drivers

Short answer: A spinlock busy-waits until the lock is free and disables pre-emption while held, so it can be used in atomic and interrupt context but must only protect very short critical sections that never sleep. A mutex puts the waiting task to sleep, so it can only be used in process context, but the holder may sleep (e.g. do I2C transfers) and hold it longer; it also enforces ownership.

Spinlock Mutex
Waiting busy-waits (spins) sleeps (other tasks run)
Usable in IRQ/softirq context yes no
May sleep while held no yes
Pre-emption while held disabled allowed
Hold time very short (microseconds) can be longer
Ownership no yes; only the owner unlocks, debug checks
On PREEMPT_RT becomes a sleeping rt_mutex (except raw_spinlock_t) rt_mutex with priority inheritance

Other primitives

  • Semaphore: counting, can be released by another task; rarely the right choice for new code.
  • rwlock / rw_semaphore: many readers or one writer.
  • Completion: "wait until X is done" (wait_for_completion, complete).
  • Atomics and RCU: lock-free options for counters and read-mostly data.

Rule of thumb: if the critical section can sleep or is long → mutex. If it is short or the data is touched from interrupt context → spinlock (with the correct irq variant). Never hold a spinlock while calling a function that might sleep.

On a single-CPU kernel without CONFIG_SMP, spinlocks reduce to disabling pre-emption (and interrupts for the _irqsave variants), because there is no other CPU to race with — but the code must still be written correctly for SMP.