Table of contents
1.
Introduction
2.
What is Mutex in OS?
3.
Working of Mutex in OS
4.
Components of Mutex Locks in OS
5.
Different Types of Mutex Locks in OS
6.
Use of Mutex in OS
7.
Thundering Herd Problem
8.
Locks and Priorities
9.
Deadlock in Mutex
10.
Advantages of Mutex in OS
11.
Disadvantages of Mutex in OS
12.
Frequently Asked Questions
12.1.
Why are the mutex needed in OS?
12.2.
What is semaphore and mutex in OS?
12.3.
What are mutex locks in OS?
13.
Conclusion
Last Updated: Mar 27, 2024
Medium

Mutex in OS

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The terms mutex and semaphore have always created chaos among scholars. These are among the important concepts of an operating system and play a vital role in achieving process synchronization in a multiprogramming environment.
A mutex is a locking mechanism that synchronizes access to a resource. The mutex can acquired by only one job (which can be a thread or process depending on the operating system abstraction). It indicates that a mutex has ownership and only the owner can release the lock.

mutex in os

This blog will help you in getting a better understanding of the topic.

Before moving on to mutex, first, let's get familiar with a few terminologies:

  1. Process Synchronization- In a multiprogramming environment, where multiple processes are present, all the processes need to be synchronized so that incorrect output is not produced.
  2. Race Condition- When two or more processes try to access the same shared variable, there is a possibility that it may produce an incorrect output which depends on the order in which access takes place.
  3. Critical Section- A region that contains the shared variables.

Also Read, Multiprogramming vs Multitasking

What is Mutex in OS?

Mutex stand for mutual exclusion object. A mutex in OS is a program object used in computer programming that allows many program threads to alternately access the same resource, such as access to a file.

A mutex is a binary variable used to provide a locking mechanism. It offers mutual exclusion to a section of code that restricts only one thread to work on a code section at a given time.

what is mutex

Working of Mutex in OS

  • Suppose a thread executes a code and has locked that region using a mutex.
  • If the scheduler decides to perform context switching, all the threads ready to execute in the same region are unblocked.
  • Out of all the threads available, only one will make it to the execution, but if it tries to access the piece of code already locked by the mutex, then this thread will go to sleep.
  • Context switching will take place again and again, but no thread will be able to access the region that has been locked until the lock is released.
  • Only the thread that has locked the region can unlock it as well.

 

This is how mutex ensures the mutual exclusion of threads in a multiprogramming environment.

Consider the given example:

int a;
mutex_lock  lock_a; //lock variable which should reside in shared memory
void thread()
{
    mutex_lock(&lock_a);
    //Some work in the thread
    &mutex_unlock(&lock_a);
}


Here, in the above example, we have defined a mutex lock for the thread function. Firstly, the thread will acquire a mutex lock when entering the critical section after completion of the work the thread will be unlocked and exit the critical section.

Components of Mutex Locks in OS

The fundamental parts that constitute mutex locks, including the lock itself, which is a synchronization mechanism preventing multiple threads from simultaneously accessing shared resources. These are several components of mutex locks:

  • Lock: The core element that signals whether a resource is currently in use
     
  • Status Indicators: Variables or flags indicating the state of the mutex, whether it's locked or unlocked
     
  • Thread Synchronization Mechanisms: Protocols or methods ensuring orderly access to the shared resource by multiple threads

Different Types of Mutex Locks in OS

There are several types of mutex locks that are designed for specific scenarios.

  1. Binary Mutex Locks: Basic on/off locks that either allow or prevent access
     
  2. Recursive Mutex Locks: Permits a thread to relock a resource it has already locked
     
  3. Adaptive Mutex Locks: Adjusts its behavior based on the current system conditions

Use of Mutex in OS

The practical application of mutex locks in programming to manage access to shared data among multiple threads. Mutexes prevent race conditions, ensuring that critical sections of code are executed by only one thread at a time, maintaining data integrity.

Thundering Herd Problem

Thundering Herd problem occurs when multiple threads are simultaneously awakened to access a shared resource. This simultaneous rush can lead to contention, inefficiency, and resource wastage due to unnecessary competition for the same resource. Solutions involve mitigating simultaneous wakes or using signaling mechanisms.

Locks and Priorities

Discusses the relationship between mutex locks and priority levels in multi-threaded systems. Priorities influence how locks are acquired, released, and managed. Considerations include avoiding priority inversion, where a high-priority thread is blocked by a low-priority one, and preventing deadlocks, ensuring efficient resource utilization.

Deadlock in Mutex

In a multiprogramming environment where two or more processes are executed, deadlock can occur using mutex during process synchronization. Deadlock occurs when threads are holding each other locks and are waiting for each other to unlock first. The four conditions for deadlock are:

  1. Mutual exclusion: There must exist at least one resource which can be used by only one resource.
  2. No preemption: The thread must release the resource by itself. Another thread can’t snatch it.
  3. Hold and wait: There must exist a resource holding a resource and waiting for another resource to be released. 
  4. Circular wait: All the processes must wait in a circular pattern.

 

Let’s try to understand deadlock in mutex through an example:

//thread1
void thread1()
{
    lock(&mutex1);
    lock(&mutex2);
    // Some work in the thread
    unlock(&mutex2);
    unlock(&mutex1);
}

//thread2
void thread2()
{
    lock(&mutex2);
    lock(&mutex1);
    // Some work in the thread
    unlock(&mutex1);
    unlock(&mutex2);
}


In the above example, there are two threads and two mutexes. This example will work smoothly if both the mutex lock the threads first, finish their job, and unlock them after completion. 
But in a multiprogramming environment, both the thread function can start simultaneously, and thread1 may acquire mutex1, and thread2 acquires mutex2, respectively. Then both go into infinite wait for the other thread to unlock the mutexes first. Thus, creating a deadlock condition. 

Must Read Process Management in OS

Advantages of Mutex in OS

  • Since there is only one thread present in the critical section at a given time, there are no race conditions, and the data always remains consistent.
  • Only one thread will be able to access the critical section
  • Solves the race condition problem

Disadvantages of Mutex in OS

  • If a thread is preempted or goes to sleep after obtaining a lock, then it may cause other threads to enter a state of starvation as they may not move forward.
  • It cannot be locked or unlocked other than the one thread that has acquired it.
  • It may lead to a busy waiting state, which wastes CPU time as the thread will check again and again for the lock to get released, hence wasting a lot of system calls.

 

To understand the difference between semaphores and mutex better refer to the article Semaphores v/s mutex.

Frequently Asked Questions

Why are the mutex needed in OS?

Mutexes are essential in operating systems to synchronize access to shared resources among multiple threads. They prevent data corruption and race conditions, ensuring that critical sections of code are executed by only one thread at a time, maintaining system integrity.

What is semaphore and mutex in OS?

Semaphores are integer variables that are primarily used to combine the two atomic processes of wait and signal for process synchronisation in order to solve the critical section problem. A mutex (mutual exclusion object) is a program object used in computer programming that allows many program threads to alternately access the same resource, such as access to a file.

What are mutex locks in OS?

A mutex lock in an operating system is essentially a binary variable that offers code-by-code capabilities for mutual exclusion. Multiple threads may occasionally be attempting to access the same resource, such as memory or I/O. to ensure there isn't an overriding. Mutex offers a locking system.

Conclusion

This article discussed Mutex in OS and all the information one needs to know about them.

Recommended Readings: 


Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, and Operating Systems.

Live masterclass