Day 85 - Semaphores

Until now we have seen two ways of solving the Critical Section Problem, By hardware and by software. Both of them have their own advantages and disadvantages. Today we will be learning about another way of solving the critical section problem and that is called Semaphores.

Semaphores

Semaphores is another way of preventing critical section problem to occur. It can be a variable or an abstract data type that is used to control access to common resources by the multiple processes. A semaphore is an integer variable that is used by oprocesses to send signal to other processes. It can only be accessed by the following two operations.

  • P (Wait or Down)
  • V (Signal or Up)

The definations of both these functions are below.

def Wait(S):
  while (S <= 0):
    # Do Something
  S = S - 1

def Signal(S):
  S = S + 1

Any change to both these operations must be executed individually and while some process is executing these operations no other process is allowed to make any chage during the execution.

Semaphores are used to solve the critical section problem for n number of processes. The processes use a shared semaphore of mutex initialized to 1. This implementation is follows.

while True:
  Wait(mutex)
    # Critical Section
  Signal(mutex)
    # Remainder Section

Here a mutex is a shared semaphore that is initialized to 1. A process P0 will execute Wait() operation which will decrement the semaphore to 0 and it will enter the critical section. Now if some other process tries to enter critical section by executing Wait() it will not be able to do that because the semaphore is 0 and it will not increment to 1 until the process P0 complete it Wait() execution and then executes Signal(). Signal() will increment mutex to 1 so some process can enter the critical section now.


zainscizainsci