Mutex v/s Semaphore v/s Spinlock

Simplify Complexity
FreeThreads
Published in
1 min readOct 9, 2021

--

Similarity

  • All of these are used for synchronization

Difference

A mutex provides singular access to a resource at a time, others must wait (sleeping) in a queue. Once the current person is done, the next in the queue acquires the resource.

So access is serial, one guy after another. There is a context switch of the requester thread if the mutex is unavailable.

Semaphore is useful to set an upper bound on a collection of resources. It is basically an atomic counter. Very useful if multiple instances (N) of a resource are shared among a set of users. As soon as all N resources are acquired, any new requester has to wait. Since there is no single lock to hold, there is no ownership of a semaphore.

Spinlock is an aggressive mutex. In mutex, if you find that the resource is locked by someone else, you (the thread/process) switch the context and wait (non-blocking).

Whereas spinlocks do not switch context and keep spinning. As soon as the resource is free, they go and grab it. In this process of spinning, they consume many CPU cycles. Also, on a uni-processor machine, they are useless.

Caution — Spinlock causes the process to be uninterruptible. Thus Spinlock is feasible only for a short wait.

--

--

Simplify Complexity
FreeThreads

Golang, Distributed Systems, File Systems, Python, C/C++, Linux