Binary Semaphore

  1. It is also known as mutex.
  2. It is made for only two processes.
Binary Semaphore (Mutex)
    struct Semaphore
    {
        enum value(0,1)   // 1 means available and 0 means not available
        Queue type L;
    }
// ‘L’ contains all PCBs (Process Control Board) to processes which got blocked 
//  while performing Down operation unsuccessfully.
    Down(BSemaphore S)
    {
        if(S.value == 1)
        {
            S.value = 0;
        }
        else
        {
            // put the process’s PCB in S.L;
            Sleep();
        }
    }

// if S’s value is 1 means someone can go to Critical section.
    
    Up(BSemaphore S)
    {
        if(S.L is empty)
        {
            S.value  = 1 ;
        }
        else
        {
            // select a process from S.L;
            S.value = 1;
            wakeup();
        }
    }

Explanation

We can refer the same from the previous concept of counting semaphore

  1. Suppose there are two processes and first one wants to go into critical section.
  2. Down function will be called and the value will become 0 and process will go into critical section.
  3. Now process 2 came and value will become 0 and else part will become true in the Down function and process will go to sleep.
  4. Process completed critical section and will call Up function and it will check whether waiting queue is empty or not, if yes then it will just increment the value otherwise it will make value =1 and wake up one process in the queue.
  5. Second process will now awake and go into critical section.





Quantitative Aptitude
Reasoning
Programming
Interview