When to use what: Mutex, semaphore and spinlock

Mutex:

  • Mutex should be used when a piece of code(CS) containing shared variables should not be executed by any other thread at the same time.
  • It ensures mutual exclusion.
  • Example: Consider a deletion of a node from a linked list, at the same time some other thread should not insert a new node and play around with the pointers.
  • The thread is blocked and put to sleep, hence involves context switching.
  • It is preferable when we have a larger CS code, else most of the time goes in context switching.
  • Having frequent context switching can seriously impact the performance of the system.

Semaphore:

  • Semaphore is a signaling mechanism and should be preferred when one thread sleep until some other thread signals it to wake up.
  • It is a kind of event-driven mechanism. once the event occurs, the signal is generated.
  • The thread which locked the semaphore variable does not take ownership, it can be signaled by another thread to unblock. Hence should not be used for mutual exclusion.
  • This can be useful in producer and consumer problems where both can signal each other once the buffer is full and empty respectively.
  • Also useful in DB thread pool, DB connection pool.

Spinlock:

  • Unlike mutex and semaphore, it does not put the thread to sleep, rather threads keep spinning and wait until the lock is available.
  • It does not involve any context switching and also preemption is disabled.
  • This should be preferred when the critical section is small and the thread does not need to sleep if the resource is not available.
  • If lead to CPU cycle wastage if the CS happens to be big.
  • One classic example is the case of interrupt in OS kernel, if this is put to sleep, the complete system gets freeze.
  • Thus any changes in the ISR code and which can face race conditions should be protected by a spinlock.


Categories: Operating system (OS)

1 reply

Trackbacks

  1. Index of Operating System - Tech Access

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: