# Semaphores, counting semaphores, binary semaphores in Operating systems OS

## What are semaphores?

Semaphores are the variables.
Semaphores are used for signaling among processes.
Three kinds of operations are performed on semaphores;

1. To initialize the semaphore
2. To increment the semaphore value
3. To decrement the semaphore value

## What are binary semaphores?

Binary semaphores take only the values between 0 to 1.

## What are counting semaphores?

Counting semaphores have the non-negative integer value.

## How can processes get the critical section?

• A critical section is controlled by semaphores by following operations;
• Wait:
• Any process can’t enter into the critical section.
• The semaphore value is decremented.
• Signal:
• The process can enter into the critical section.
• The semaphore value is incremented.

### Wait and Signal Operations in Semaphores

We can implement Wait and Signal Operations in process synchronization. The actual purpose of Wait and Signal operation is to get mutual exclusion.

### The Wait Operation in Semaphores

The wait operation decrements the value of Semaphore if it is positive. If Semaphore is negative or zero, then no operation is performed.

wait(Semaphore)
{
while (Semaphore<=0);

Semaphore–;
}

## Signal Operation in Semaphores

The signal operation increments the value of Semaphore.

signal(Semaphore)
{
Semaphore++;
}

## Semaphores implementation in C++

Now, let’s see theC++ Program for Semaphores.

Output

For example, in this example, we can see in our output screenshot that when we select choice 1, then the program gives a chance to the Reader process to enter into the critical section. Now, if the writer process wants to enter into the critical section, then semaphore stops it. When the reader process is removed, then semaphore can allow the writer process to enter into the critical section.

## Difference between Binary Semaphore Â VS Counting Semaphore

Let’s see some common difference between binary Â and counting semaphore:

 Binary Semaphore Counting Semaphore Mutual exclusion No mutual exclusion Semaphore Value is only 0 and 1 Semaphore Value is any integer value The only process at the same time. Can provide a set of Processes Only one slot More than one slot

Some of the advantages of semaphores are mentioned below:

• Semaphores strictly follow the principle of mutual exclusion and allow only one process into the critical section at the same time.
• Semaphores are machine-independent, so Semaphores are implemented in the machine-independent code of the microkernel.
• Semaphores allow flexible management of resources.
• Semaphores can be considered as more efficient than other methods of synchronization.