Explain briefly the working of semaphore with example ?
The E.W. Dijkstra (1965) abstracted the key idea of mutual exclusion in his concepts of semaphores.
Definition
A semaphore is a confined variable whose value is able to be accessed and altered only by the operations P and V and initialization operation called as 'Semaphoiinitislize'.
Binary Semaphores is able to assume only the value 0 or the value 1 counting semaphores as well called general semaphores can assume only nonnegative values.
The P or sleep or wait or down operation on semaphores S written as P(S) or wait (S) operates as follows:
P(S): IF S > 0
THEN S:= S-1
ELSE (wait on S)
The V or wakeup or signal or up operation on semaphore S written as V(S) or signal (S) operates as follows:
V(S) IF (one or more process is waiting on S)
THEN (let one of these processes proceeds)
ELSE S: = S +1
Operations P and V are complete as indivisible, single, atomic action. It is guaranteed that formerly a semaphore operation has stared, no other process are able to access the semaphore until operation has completed. The Mutual exclusion on the semaphore S is enforced within P(S) and V(S).
If several processes attempt a P(S) concurrently only process will be allowed to proceed. The other processes will be set aside waiting however the implementation of P and V guarantees that processes will not suffer indefinite postponement.
Semaphores resolve the lost-wakeup problem.