/    /  OS – Semaphore

Semaphore

 

Semaphore is a variable used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment. 

It is a non-negative variable that is shared between the threads. 

 

There are two types of Semaphores:

  • Binary Semaphore: It is also known as Mutex Lock. It has two values 1 and 0, the value is initialized to 1.  
  • Counting Semaphore: The value can range over an unrestricted domain. Counting Semaphore is used to control access to a resource that has multiple instances. 

Example of a Semaphore:

 

Let’s look at the following example that involves step by step implementation of Semaphore:

 

There are two operations in Semaphores used to implement Process Synchronization:

  • Wait for Operation

It helps you control the entry of a task in the critical section.

  • Signal Operation

It helps you control the exit of a task from the critical section.

 

Counting Semaphore vs Binary Semaphore:

 

Counting SemaphoreBinary Semaphore
It provides more than one slot.It provides one slot.
It provides a set of processes.It has mutual exclusion mechanism.
Any value. Only 0 and 1. 

 

Advantages of Semaphore:

 

The advantages of Semaphore are as follows:

  1. It allows flexible management of resources. 
  2. It is machine-independent.
  3. It allows multiple threads to access the critical section. 
  4. It does not allow multiple processes to access the critical section at the same time.

Disadvantages of Semaphore:

The disadvantages of Semaphore are as follows:

  1. Priority inversion.
  2. The OS needs to keep track of Wait and Signal operations.
  3. This is not a practical method for large-scale use.
  4. It may cause deadlock if the Wait and Signal operations are executed in the wrong order.

 

Reference

Semaphore In Os