what is semaphore in os

what is semaphore in os

1 year ago 65
Nature

Semaphore is a mechanism used in operating systems for process synchronization. It is a non-negative integer variable that is shared between threads or processes. Semaphores are used to address critical section problems by using two atomic operations, wait and signal, for process synchronization. The wait operation decrements the value of the semaphore, and if it is zero or negative, then no operation is performed. The signal operation increments the value of the semaphore. Semaphores are of two types: binary semaphore and counting semaphore.

Binary semaphore is also known as a mutex lock. It can only have two possible values: 0 and 1, and its value is set to 1 by default. It is used to control access to a resource that has multiple instances. Counting semaphore uses a count that helps tasks to be acquired or released multiple times. If the initial count is 0, the counting semaphore should be created in the unavailable state.

Semaphores allow only one process into the critical section, and they follow the mutual exclusion principle strictly. They are much more efficient than some other methods of synchronization, and there is no resource wastage because of busy waiting in semaphores as processor time is not wasted unnecessarily to check if a condition is fulfilled to allow a process to access the critical section.

Semaphores are implemented in the machine-independent code of the microkernel, so they are machine-independent. However, they are complicated, so the wait and signal operations must be implemented in the correct order to prevent deadlocks. Semaphores may lead to a priority inversion where low priority processes may get the semaphore before high priority processes.

Read Entire Article