Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Spinlocks vs Mutexes
OS

Spinlocks vs Mutexes

When to use a spinlock, when to use a mutex, and the performance trade-offs.

Both spinlocks and mutexes provide mutual exclusion, but they handle contention very differently.

How They Work

SpinlockMutex
Waiting threadBusy-waits (spins in a loop)Sleeps (yields CPU, context switch)
CPU usage while waiting100% — wasting CPU cycles~0% — thread is not scheduled
Latency when lock releasedImmediate (already running)Scheduler must awaken sleeping thread
Best forShort critical sections, < ~100 cyclesLong critical sections, I/O waits

When to Use Which

Use a spinlock when:

  • Critical section is very short (just a few instructions)
  • You’re in an interrupt handler or atomic context where sleeping is illegal
  • You’re on a multi-core system (spinlock on single core = deadlock)

Use a mutex when:

  • Critical section is long (I/O, network, disk)
  • Contention is high (many threads competing)
  • Power consumption matters (spinning wastes energy)

The Decision Tree

Lock needed?
├─ Critical section << context switch time (< 100 cycles)?
│  └─ YES → Spinlock (spinning is cheaper than sleeping)
├─ Running in atomic/IRQ context?
│  └─ YES → Spinlock (can't sleep in IRQ handler)
├─ Single-core CPU?
│  └─ YES → Disable preemption (spinlock is pointless here)
└─ Otherwise → Mutex (or adaptive mutex)

Linux Adaptive Mutex

Modern Linux uses an adaptive mutex: spin a few times, then sleep if the lock isn’t released quickly. Combines the best of both approaches.

Spinlock Implementation (Conceptual)

void spin_lock(atomic_t *lock) {
    while (atomic_test_and_set(lock, 1) == 1) {
        // CPU relaxation instruction (pause/yield)
    }
}

void spin_unlock(atomic_t *lock) {
    atomic_set(lock, 0);
}

Q: When is a spinlock better than a mutex?

A: When the critical section is very short (< ~100 CPU cycles) and you have multiple CPU cores. The cost of spinning is less than the cost of a context switch. Also, you must use spinlocks in interrupt handlers where sleeping isn’t allowed.

Q: Why is a spinlock bad on a single-core CPU?

A: If the lock holder doesn’t yield the CPU, the spinner will spin forever — it’s the same thread. On single-core, you must use a mutex (which sleeps and lets other threads run) or disable preemption.

Q: What is busy-waiting?

A: The thread keeps executing (checking the lock in a loop) without making progress. It wastes CPU cycles doing nothing useful. Acceptable only when the wait is guaranteed to be extremely short.

Q: How does Linux handle this choice?

A: Linux uses an adaptive mutex in most cases — it spins for a short while before sleeping. This captures the fast case (short critical section) without the risk of long busy-waiting.

My Private Notes

Notes are auto-saved locally to this device.