Semaphore
A semaphore is a non-negative integer variable that is shared between various threads. Semaphore works upon signaling mechanism, in this a thread can be signaled by another thread. Semaphore uses two atomic operations for process synchronisation:
- Wait (P)
- Signal (V)
Advantages of Semaphore
- Multiple threads can access the critical section at the same time.
- Semaphores are machine-independent.
- Only one process will access the critical section at a time, however, multiple threads are allowed.
- Semaphores are machine-independent, so they should be run over microkernel.
- Flexible resource management.
Disadvantages of Semaphore
- It has priority inversion.
- Semaphore’s operation (Wait, Signal) must be implemented in the correct manner to avoid deadlock.
- It leads to a loss of modularity, so semaphores can’t be used for large-scale systems.
- Semaphore is prone to programming error and this can lead to deadlock or violation of mutual exclusion property.
- Operating System has to track all the calls to wait and signal operations.
Using Semaphore
The producer-consumer problem: Consider the standard producer-consumer problem. Assume, we have a buffer of 4096-byte length. A producer thread collects the data and writes it to the buffer. A consumer thread processes the collected data from the buffer. The objective is, both the threads should not run at the same time.
Solution- A semaphore is a generalized mutex. In lieu of a single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.
Note: The content is a generalized explanation. Practical details vary with implementation.
Mutex vs Semaphore
In the Operating System, Mutexes and Semaphores are kernel resources that provide synchronization services (also known as synchronization primitives). Synchronization is required when multiple processes are executing concurrently, to avoid conflicts between processes using shared resources.