# How can a binary semaphore implement mutual exclusion among n processes?

A semaphore is a shared variable which is used to implement mutual exclusion between system processes. It is mainly helpful to solve critical section problems and is a technique to achieve process synchronization.

### There are two types of semaphores which are as follows −

• Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.

• Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.

### Critical section is surrounded by P and V operations as follows −

• P(s)

• CS

• V(s)

Each of these operations is defined below −

Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue.

P(Semaphore s)
{
s = s - 1;
if (s < 0) {
block(p);
}
}

Signal(V) − When a process exists CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation.

V(Semaphore s)
{
s = s + 1;
if (s >= 0) {
wakeup(p);
}
}

Now let see how binary semaphore can be used to implement mutual exclusion among n processes.

We know that semaphore is a variable that can be used to control access by multiple processes to a common resource in multitasking OS. As per the question suppose if there are n processes that commonly share a semaphore to each process then process allocation is organized based on the following algorithm.

do {
wait(mutex);
signal(mutex);
} while (true);

### Explanation

It is processed using a do-while loop that means it performs 'do' conditions until we get satisfied while condition.

Here it performs wait and signal operations of mutex until it becomes true.

Updated on: 02-Dec-2021

1K+ Views