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.
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.
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.
Working of Mutex
·
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.