DEV Community

Cover image for Binary Semaphore | Operating System - M03 P06
Rahul Mishra
Rahul Mishra

Posted on • Updated on • Originally published at programmingport.hashnode.dev

Binary Semaphore | Operating System - M03 P06

This is a multipart blog article series, and in this series I am going to explain you the concepts of operating system. This article series is divided into multiple modules and this is the third module which consists of 10 articles.

In this article we will see that what is binary semaphore and how does it work, in order to achieve synchronization and remove race condition.

Binary semaphore

  • The counting semaphore has a range of – infinity to + infinity but in binary semaphore there are only two values 0 and 1.
  • Binary semaphores are used more in systems then counting semaphore.

Untitled Diagram.png
Entry section pseudo code

Down(Semaphore S) {
    if (Svalue = 1) {
        Svalue = 0;
    }
    else {
        Block this process and place in suspend list, Sleep();
    }
}
Enter fullscreen mode Exit fullscreen mode

Exit section pseudo code

Up(Semaphore S) {
    if(Suspend list is empty) {
        Svalue = 1;   
    }
    else {
        Select a process from suspend list and wake up();
    }
}
Enter fullscreen mode Exit fullscreen mode
  • If the value of S is 1 and then it become 0 after performing Down operation, then it is considered as successful operation.
  • If the value of S is 0 and then process execute Down operation, then in that case the process will be block/sleep and it will be sent to suspended list, it will be considered as unsuccessful operation.
  • The Up operation first check that if the suspended list is empty or not, and if it is empty then it will change the value of S to 1, does not matter that what was the value the value of S, if the value of S previously was 0 then it will become 1 and if it 1 then it will remain 1.
  • If the suspended list is not empty then else part will be executed and the process in the block/sleep state will get wake up and then get a chance to try to go in critical section by executing the Down operation.

So, this was all about binary semaphore. Hope you liked it and learned something new from it.

If you have any doubt, question, quires related to this topic or just want to share something with me, then please feel free to contact me.

📱 Contact Me

Twitter
LinkedIn
Telegram
Instagram

📧 Write a mail

rahulmishra102000@gmail.com

🚀 Other links

GitHub
HackerRank

Top comments (0)