Semaphore
Semaphores are a synchronization mechanism used to
coordinate the activities of multiple processes in a
computer system. They are used to enforce mutual
exclusion, avoid race conditions and implement
synchronization between processes.
Semaphores provide two operations:
wait (P) and signal (V).
The definition of wait operation is
wait(S):
The definition of signal operation is
signal(S):
The wait operation decrements the value of the
semaphore, and the signal operation increments the
value of the semaphore. When the value of the
semaphore is zero, any process that performs a wait
operation will be blocked until another process performs
a signal operation.
Semaphores are used to implement critical sections,
which are regions of code that must be executed by only
one process at a time. By using semaphores, processes
can coordinate access to shared resources, such as
shared memory.
Semaphore are of two types:
1.Binary Semaphore –
This is also known as a mutex lock. It can have only two
values – 0 and 1. Its value is initialized to 1. It is used to
implement the solution of critical section problems with
multiple processes.
2. Counting Semaphore –
Its value can range over an unrestricted domain. It is
used to control access to a resource that has multiple
instances.
The implementation of semaphore may lead to two
problems as it tries to enforce the mutual exclusion for
the critical section problems.
1. deadlock- Implementation of semaphore with a wait
queue may result in situation where two or more
processes are waiting indefinitely for an event that can
be caused by only one of the waiting processes.
For ex: Consider a system consisting of two processes,
P0 and P1 each accessing two semaphores S and Q, set
with value 1.
P0 executes wait(S), P1 executes wait(Q). When P0
executes wait(Q), it must wait until P1 executes
signal(Q). Similarly, when P1 executes wait(S), it must
wait until P0 executes signal(S). Since these signal
operations cannot be executed, P0 and P1 are
deadlocked.
Another problem is indefinite blocking or starvation, a
situation where processes wait indefinitely within the
semaphore.