Course contentsShow
← Computer Science
Lesson 1287 of 2,87230. Process SynchronizationFree lesson

Spin Locks vs Blocking Locks

Comparing spin locks (busy-wait in user space) with blocking locks (yield CPU, suitable for longer waits).

Spin Locks vs Blocking Locks

You'll learn: The difference between busy-waiting spin locks and CPU-yielding blocking locks, and when to use each.

The Core Difference

When a thread can't acquire a lock immediately, it has two basic strategies:

  1. Spin lock: Keep trying repeatedly in a tight loop (busy-waiting)
  2. Blocking lock: Ask the OS to put the thread to sleep and wake it later

Think of it like waiting for a bathroom: you can either pace back and forth continuously checking the door handle (spinning), or you can sit down elsewhere and ask someone to tap you when it's free (blocking).

When to Spin

Spin locks are efficient when the critical section is very short (a few microseconds). The thread stays active in user space, burning CPU cycles but avoiding the overhead of context switching. If the lock will be free almost immediately, spinning wins.

Drawback: Wastes CPU time if the wait is long. Other threads that could do useful work are starved of CPU resources.

When to Block

Blocking locks (like pthread mutexes in their default behavior) are better when the wait might be longer. The thread yields the CPU via a system call, allowing other threads to run. When the lock becomes available, the OS wakes the waiting thread.

Drawback: Context switching overhead (saving/restoring state, kernel transition) makes blocking expensive for very short waits.

The Trade-off

  • Spin locks: Low overhead, but waste CPU during wait
  • Blocking locks: Higher initial overhead, but efficient use of CPU during wait

Some implementations use adaptive mutexes that spin briefly, then block if the lock isn't acquired quickly.

Key Takeaway: Spin locks busy-wait in user space (good for short critical sections), while blocking locks yield the CPU (better for longer waits or when CPU efficiency matters).