1. Home
Operating System

OS Tutorial: Learn Operating Systems Basics

Learn Operating System fundamentals: concepts, processes, memory management, and more. Start your journey to mastering OS with our comprehensive tutorial.

  • 47
  • 7 Hours
right-top-arrow

Tutorial Playlist

47 Lessons
20

Semaphore in Operating System

Updated on 19/07/2024458 Views

Semaphore is an important concept to learn if you want to know how an Operating System manages shared system resources. It is a very crucial topic upon which questions appear in all sorts of computer science-based competitive exams. Having years of experience with OS (Operating Systems), let me walk you through the fundamental concepts of how a semaphore in OS works.

To start this tutorial, let me first define semaphore in OS.

In its most basic form, a semaphore in OS is a variable that manages resource access. It might contain a number that represents how many slots or resources are available for use by processes. A process looks up the semaphore when it wants to use the resource.

What is Semaphore in Operating System?

To understand a semaphore in OS example compared to real life, let us take the role of semaphore in OS and compare it with the role of a cop in real life managing traffic. The semaphore is like a police officer of the operating system. It distributes shared resources among various processes.

Imagine you have several processes trying to get the same resource. Much like a police officer maintaining traffic, if the police officer does not make sure the traffic lights are coordinated and every car is unorganized, it would wreak havoc. This would result in crashes left and right.

Similarly, semaphore needs to coordinate which processes get access to shared resources at a particular time to avoid a lot of problems. It can lead to deadlocks, race conditions, and more if not implemented correctly.

History of Semaphores in Operating Systems

Before I explain semaphore in OS, let's take a quick look at their backstory. Knowing where they came from can help us understand their purpose better and might even come in handy during interviews!

The story starts with a Dutch computer scientist named Edsger Dijkstra, the same person we know from Dijkstra's algorithm. He proposed the use of semaphores to tackle the issue of sharing resources between simultaneously running processes. The name semaphores is taken from the maritime industry where it means to signal something using flags. He introduced two actions related to semaphores namely wait(also known as "P" operation) and signal(also known as "V" operation).

Semaphores have evolved and improved over time to meet a variety of simultaneous processing difficulties and requirements in operating systems. Different types of semaphores, such as binary and counting semaphores, have been developed to meet various synchronization scenarios and resource management duties.

Types of Semaphore in OS

There are mainly two types of semaphore in OS. Let me explain them in detail to you.

Binary Semaphores

In this section, let me explain binary semaphore in OS with some key pointers:

  • Binary semaphore in OS is one of the most basic types. It is, sometimes also referred to as mutexes which is short for mutual exclusion.
  • There are just two possible integer values for them: 0 and 1.
  • When only one process or thread can access shared resources at a time, binary semaphores are usually employed to control access.
  • They are frequently used to guarantee exclusive access to important code segments or shared resources and to prevent race situations.

Counting Semaphores

Now, let me explain counting semaphores. They are both more complex to implement and difficult to debug.

  • Many threads or processes can access a shared resource at once when counting semaphores have values higher than or equal to zero.
  • When there is a cap on the quantity of resources available, they are used to manage access to a pool of resources that are all the same.
  • When multiple instances of a resource can be used at the same time, like when managing a fixed number of buffers, printer instances, or database connections, counting semaphores is useful.
  • To maintain correct synchronization, processes or threads can increase or decrease the semaphore value in response to resource availability and utilization in real time.

Operating systems use these two kinds of semaphores as basic synchronization techniques to help simultaneous processes or threads coordinate and communicate with one another for shared resources. Developers can use binary or counting semaphores to design efficient synchronization techniques, depending on the particular requirements of a given application or system.

Working Principle of a Semaphore in OS

We already know semaphores in OS work as a resource coordinator. But ever wondered how it functions? Let me explain semaphore in OS step by step here.

1. Initialization

A certain value is initialized for semaphores. While counting semaphores can have any non-negative integer as their initialization, binary semaphores typically have one of two possible values.

2. Wait Operation(Acquiring Semaphore)

A thread or process tries to get the semaphore linked to a shared resource in order to gain access to it. How this operation is performed defines if a semaphore is binary or counting in nature. In the case of binary semaphores, the counter value keeping track of resources only has two states. In the case of counting semaphores, the value of the counter variable is not limited between two states of only 0 and 1.

  • For binary semaphores, the process checks if the semaphore counter value is 1 (indicating the resource is available). If it is 1, the process reduces the semaphore value to 0 and proceeds to use the resource.

    If the semaphore value is 0, indicating the resource is currently being used, the process may be suspended or blocked until the semaphore becomes available (when the semaphore value becomes 1).
  • Similar checks are made to see if the semaphore value is larger than 0 while counting semaphores. In that case, the value is decreased and resource access is continued.

    If the value is 0, the process will either wait or stop until the semaphore is released by another process, increasing its value. It is mainly used in semaphore in real time operating system processes where there are multiple processes dependent on a single resource.

Signal Operation (Releasing Semaphore)

A process or thread releases the semaphore linked to it once it has completed using the shared resource.

  • When a process uses a binary semaphore, it increases the value of the semaphores from 0 to 1, signaling that another process can not utilize the resource. This is the case for binary semaphores.
  • The process increases the semaphore value if the resource is busy from 0. But in the case of counting semaphores, as the value of the semaphore is not limited to only 1 and 0, it can account for the priority of processes and will execute a process first with higher priority.

Blocking and Waking Up A Process

The working of a semaphore in OS also uses two processes called blocking and wakeup. Let us understand what are they.

  • A process may go into a blocked state and wait for the semaphore to become free if it tries to get one but is unsuccessful.
  • A process may wake up one or more previously stalled processes and allow them to continue executing when it releases a semaphore.

Mutual Exclusion and Atomicity

In this section, let me explain the concept of mutual exclusion and atomicity:

  • Operations on semaphores are typically implemented as atomic operations(operations that do not get interrupted by another process when they get executed) to prevent race conditions.
  • Other synchronization techniques, such as locks or atomic instructions, are frequently used to safeguard access to the semaphore itself in order to maintain mutual exclusion and stop concurrent change by several processes.

Advantages of Semaphores in OS

Semaphores are very useful in the realm of OS. Let me tell you about all the advantages provided by semaphores in the context of OS.

  • They serve to ensure that important parts of a process that use shared resources can function in a controlled and orderly way, avoiding race situations and data corruption.
  • There are several varieties of semaphores, including binary and counting semaphores, which provide versatility for different use cases. Binary semaphores are used for applications requiring exclusive access to a resource, whereas counting semaphores allows several processes to access a pool of resources simultaneously.
  • Semaphores are efficient synchronization techniques that are frequently used with low-level atomic operations or hardware-supported synchronization techniques. They have lower overhead than higher-level synchronization techniques, making them necessary for performance-sensitive applications.
  • Semaphores help to avoid deadlock situations by offering a structured approach to govern resource access and process synchronization.
  • Semaphores can be used to prevent priority inversion(where a low-priority activity holds a resource required by a higher-priority operation). Processes are put in place so that a low-priority process does not hog resources and high-priority processes are executed first.
  • Semaphores also separate synchronization problems from application logic, hence improving code maintainability and readability.

Disadvantages of Semaphores in OS

While semaphores are very important for synchronizing processes and resources in OS, they also have their fair share of problems. Let me discuss some with you.

  • Semaphores are often difficult to implement and if done not correctly can lead to a lot of problems. Bugs such as deadlock, livelock, or race conditions can occur if not done properly.
  • Semaphores can cause priority inversion concerns when a low-priority task holds a semaphore required by a higher-priority activity, leading the high-priority process to be delayed. Priority inheritance(to let semaphores know which task is high-priority and which is low-priority is thus needed to avoid this.
  • Although semaphores are generally efficient synchronization techniques, they nevertheless have considerable overhead owing to context switching, blocking, and waking up processes. Sometimes in complex systems, it may lead to heavy performance drops.
  • Semaphores are difficult to debug. Especially in complex systems, reproducing bugs can be a challenge let alone fixing it. This is because the bugs produced are generally subtle and thus require advanced debugging techniques.

Conclusion

To sum up, a semaphore in OS is extremely important for the optimal functioning of an operating system. We have learned different types of semaphores, and their use cases to build robust and efficient operating systems.

To pursue a career in this field, you will need more insight into complex theories just like semaphores. Looking into courses from upGrad might be a good place to start. Their courses are affiliated with some of the best colleges around the world and are curated with the best professors in the field.

FAQs

  1. What is a semaphore in operating systems?

A semaphore in OS is a coordination tool that controls access to shared resources used by different simultaneously working processes or threads.

  1. What are the potential issues with semaphores?

Incorrect implementation of semaphores can lead to a lot of problems. Semaphores wrongly implemented can lead to deadlocks, resource hogging, and overhead issues.

  1. What are the types of semaphores?

There are mainly two types of semaphores. They are binary semaphores and counting semaphores.

  1. Why is it called a semaphore?

The term ‘Semaphore’ comes from the maritime industry meaning “signaling”.

  1. What are the advantages of using semaphores?

There are a lot of advantages to using semaphores. Some of them are better efficiency, deadlock prevention, and bug prevention.

  1. When should I use semaphores?

You should use semaphores to control the distribution of shared resources between processes

  1. Can semaphores be used across different processes or threads?

Yes. semaphores can be used across different processes and threads.

  1. Are semaphores the only synchronization mechanism available in operating systems?

No, other synchronization mechanisms like mutexes, condition variables, monitors, read-write locks, barriers, and atomic operations also exist in operating systems.

Mukesh Kumar

Mukesh Kumar

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...