Related Tags

semaphore
synchronization

# What is a semaphore? Educative Answers Team

A semaphore is a variable that is used to allow process synchronization. Semaphores work on a specific condition and allow the processor to communicate between multiple processes. A semaphore can have a value of 1 or 0.

## Two operations

A semaphore has two operations:

1. wait();
2. signal();

### wait()

This operation decrements the value of the semaphore by 1, i.e., s = s - 1;.

void wait(semaphore s)
{

while(s == 0); //the semi-colon
//ensures that the code is stuck while s=0
s = s - 1;     //this tells the processor that now the wait is over.

}



### signal()

This operation increments the value of the semaphore by 1, i.e., s = s + 1;.

void signal(semaphore s)
{

s = s + 1;  //this tells the processor that now the signal is done.

}



A semaphore allows two processes to exclusively run their critical section. This means that each process can run the non-mutual code (the code that is not shared between the two processes) alone. This also allows maximum processor power and zero interruption from the other processes.

The following diagram shows how a semaphore uses wait() and signal() to exclusively run the critical sections of the two processes​. ## How it works

Suppose that two processes exist (i.e., process A and process B). If A enters into its critical section, it makes the semaphore s = 0. If B wants to enter into its critical section, then it will have to wait for the moment when s becomes positive (i.e., s > 0) which will only happen if A finishes its critical section and calls the signal() function to increment the value of semaphore s.

The following table explains this better:

Phase Value of s Process A Process B
Phase 1 s = 1 Running the non-critical section. Running the non-critical section.
Phase 2 s = 1 Enters in the critical section and sets the value of s = 0 (calls wait()). Running the non-critical section.
Phase 3 s = 0 Running the critical section. This process wants to enter into the critical section, but can’t ​since the value of s = 0 (look at the wait() implementation above; the code is stuck in the while loop).
Phase 4 s = 0 Exits critical section and updates the value of s to 1. Waiting for s to be equal to 1.
Phase 5 s = 1 Running the non-critical section. Enters the critical section as s = 1. It also updates the value of s back to zero.

RELATED TAGS

semaphore
synchronization 