Semaphore
Semaphore is a variable used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment.
It is a non-negative variable that is shared between the threads.
There are two types of Semaphores:
- Binary Semaphore: It is also known as Mutex Lock. It has two values 1 and 0, the value is initialized to 1.
- Counting Semaphore: The value can range over an unrestricted domain. Counting Semaphore is used to control access to a resource that has multiple instances.
Example of a Semaphore:
Let’s look at the following example that involves step by step implementation of Semaphore:
There are two operations in Semaphores used to implement Process Synchronization:
- Wait for Operation
It helps you control the entry of a task in the critical section.
- Signal Operation
It helps you control the exit of a task from the critical section.
Counting Semaphore vs Binary Semaphore:
Counting Semaphore | Binary Semaphore |
It provides more than one slot. | It provides one slot. |
It provides a set of processes. | It has mutual exclusion mechanism. |
Any value. | Only 0 and 1. |
Advantages of Semaphore:
The advantages of Semaphore are as follows:
- It allows flexible management of resources.
- It is machine-independent.
- It allows multiple threads to access the critical section.
- It does not allow multiple processes to access the critical section at the same time.
Disadvantages of Semaphore:
The disadvantages of Semaphore are as follows:
- Priority inversion.
- The OS needs to keep track of Wait and Signal operations.
- This is not a practical method for large-scale use.
- It may cause deadlock if the Wait and Signal operations are executed in the wrong order.
Semaphore In Os