Mutexes VS Spinlocks: Choosing the Right Locking Mechanism

oceanO
3 min readSep 6, 2023

--

Mutex: When a thread tries to acquire a mutex and it’s unavailable, the thread is put to sleep. It wakes up when the mutex is available again.

Spinlock | Busy waiting | Polling: Instead of sleeping, a thread will continuously poll until the lock is available.

To give one simple analogy, Polling is the act of “continuously scrolling” the phone for social updates. Mutexes act like notifications,waking you up” only when someone actually commented, liked, sent a message ecc.

We agree that scrolling is just a waste of time? .. even though we all do that.

Our forebrain CPU is in an endless SCROOL-LOOP. If we only used MUTEXES…

According to Tanenbaum, staring the phone is a good solution if you are waiting for a message that is allegedly coming very soon.

quote from “Modern Operating Systems”, Tanenbaum.

Indeed blocking the phone and putting it into your pocket, to take it again immediately and unblock is the real time-consuming action in this case. Blocking the phone makes sense only if you will not use it in the following seconds!

This analogy boils down to the USER-KERNEL switch that happens when a sys call is made, like inside a mutex with the sleep sys. I wrote an article about this switching ⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎⬇︎.

Transitioning a thread between sleeping and running states has overhead. If a mutex is held only for a brief period, the overhead of waking up a sleeping thread can outweigh the benefit. Conversely, a spinlock can be wasteful, as a thread continuously polling for a lock consumes CPU cycles.

Single-core vs. Multi-core

On a single-core system, spinlocks aren’t usually efficient. If a thread is busy spinning, no other thread can execute, making spinlocks counterproductive. However, on multi-core systems, the scenario differs. If a lock is held briefly, spinning can avoid the overhead of putting threads to sleep and waking them up, potentially increasing performance.

Which One to Use?

For most applications, mutexes are the safer bet. However, if you suspect that a spinlock could be more efficient for your use case, you should give it a go.

A spinlock is not a wrong solution per se, it can be wrong in a context. Indeed spin locks and mutexes can be useful for different purposes. Spin locks might have lower overall overhead for very short-term blocking, and mutexes might have lower overall overhead when a thread will be blocked for longer periods of time.

TL;DR

Mutexes and spinlocks, while serving similar purposes, have distinct use cases. The choice depends largely on the specific scenario and the architecture in question. Always start with the safer and more general approach (mutexes) and then optimize based on performance measurements and specific requirements.

--

--