Mutex in os

 Mutex in os

                                                   Mutex

 Mutual Exclusion locks, or mutexes can be used to synchronize access to state and safely access data across many goroutines. It acts as a guard to the entrance of the critical section of code so that only one thread can enter the critical section at a time.

We set a lock around particular lines of code with it. While one Goroutine holds the lock, all other Goroutines are prevented from executing any lines of code protected by the same mutex, and are forced to wait until the lock is yielded before they can proceed.

Mutex is a mutual exclusion object that synchronizes access to a resource. It is created with a unique name at the start of a program. The mutex locking mechanism ensures only one thread can acquire the mutex and enter the critical section. This thread only releases the mutex when it exits in the critical section.

It is a special type of binary semaphore used for controlling access to the shared resource. It includes a priority inheritance mechanism to avoid extended priority inversion problems. It allows current higher priority tasks to be kept in the blocked state for the shortest time possible. However, priority inheritance does not correct priority inversion but only minimizes its effect.

Advantages of Mutex

  • Mutex is just simple locks obtained before entering its critical section and then releasing it.
  • Since only one thread is in its critical section at any given time, there are no race conditions, and data always remain consistent.


Disadvantages of Mutex

  • If a thread obtains a lock and goes to sleep or is preempted, then the other thread may not move forward. This may lead to starvation.
  • It can't be locked or unlocked from a different context than the one that acquired it.
  • Only one thread should be allowed in the critical section at a time.
  • The normal implementation may lead to a busy waiting state, which wastes CPU time.