DEV Community

Cover image for Mutex vs Spinlock: When Should a Thread Sleep or Spin?
Binary Dose
Binary Dose

Posted on Originally published at binarydose.in

Mutex vs Spinlock: When Should a Thread Sleep or Spin?

Mutex vs Spinlock: When Should a Thread Sleep or Spin?

In multi-threaded software engineering, managing shared mutable state requires synchronization primitives to enforce Mutual Exclusion.

Yet choosing between a Mutex, a Spinlock, and a Semaphore is not a matter of syntax—it is a hardware-level trade-off between CPU Context Switching Latency and CPU Cycle Waste.


1. Mutex: Sleep-Waiting with Strict Ownership

A Mutex is a binary synchronization primitive with ownership semantics: only the thread that locks a mutex is legally permitted to unlock it.

Mechanics:

When thread T₁ attempts to acquire a contested mutex:

  1. The kernel transitions T₁ from RUNNING to BLOCKED.
  2. T₁'s register state is saved, and the CPU schedules another thread.
  3. When the lock is released, the kernel moves T₁ back to the READY queue.

The Overhead Cost:

A mutex operation incurs two full context switches (descheduling + rescheduling). On modern x86/ARM hardware, this represents roughly 1µs - 5µs of latency, accompanied by L1/L2 cache pollution.


2. Spinlock: Busy-Waiting with Atomic Hardware

A Spinlock does not surrender the CPU core. Instead, it loops in place executing atomic instructions (such as lock cmpxchg or test_and_set).

// Conceptually:
while (__atomic_test_and_set(&lock, __ATOMIC_ACQUIRE)) {
    #if defined(__x86_64__)
    __builtin_ia32_pause(); // Emits PAUSE instruction to prevent pipeline stalls
    #endif
}
Enter fullscreen mode Exit fullscreen mode

Advantages & Disadvantages:

  • Advantage: Zero context-switch cost. Acquisition latency is measured in nanoseconds.
  • Disadvantage: Burns 100% of an entire CPU core while spinning. If the thread holding the lock is preempted, the spinning thread starves the system.
  • Rule: Mandatory in Interrupt Service Routines (ISRs) because hardware interrupt handlers cannot sleep.

3. The Mathematical Rule of Thumb

Let T_ctx be the time required for a context switch, and T_hold be the average time a thread holds the critical section:

If T_hold < 2 · T_ctx implies Use a Spinlock
Enter fullscreen mode Exit fullscreen mode
If T_hold > 2 · T_ctx implies Use a Mutex
Enter fullscreen mode Exit fullscreen mode

Explore interactive concurrency state machines at Binary Dose.

Top comments (0)