Semaphores are system-implemented data structures that are shared between processes.A semaphore is a protected variable whose value can be accessed and altered only by the operations P and V and initialization operation called ‘Semaphoiinitislize’.
TYPES OF SEMAPHORES:
- Binary semaphore (mutex semaphore)
–sem is initialized to 1
–guarantees mutually exclusive access to resource (e.g., a critical section of code)
–only one thread/process allowed entry at a time
- Counting semaphore
–sem is initialized to N
- N = number of units available
–represents resources with many (identical) units available
–allows threads to enter as long as more units are available
Binary Semaphores can assume only the value 0 or the value 1 counting semaphores also called general semaphores can assume only nonnegative values.
The P (or wait or sleep 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 signal or wakeup or up) operation on semaphore S, written as V(S) or signal (S), operates as follows:
V(S): IF (one or more process are waiting on S)
THEN (let one of these processes proceed)
ELSE S := S +1
Operations P and V are done as single, indivisible, atomic action. It is guaranteed that once a semaphore operations has stared, no other process can access the semaphore until operation has completed. Mutual exclusion on the semaphore, S, is enforced within P(S) and V(S).
If several processes attempt a P(S) simultaneously, only process will be allowed to proceed. The other processes will be kept waiting, but the implementation of P and V guarantees that processes will not suffer indefinite postponement.
Semaphores solve the lost-wakeup problem.
Features of Semaphores:
Semaphores are used to synchronize operations when processes access a common, limited, and possibly non-shareable resource.
Each time a process wants to obtain the resource, the associated semaphore is tested. A positive, non-zero semaphore value indicates the resource is available.
Semaphore system calls will, by default, cause the invoking process to block if the semaphore value indicates the resource is not available.
USES OF SEMAPHORES:
Critical Section Guard (initial value: 1)
- Semaphores that control access to a single resource, taking the value of 0 (resource is in use) or 1 (resource is available), are often called binary semaphores.
Precedence Enforcer (initial value: 0)
- Semaphores ensuring an ordering of execution among concurrent processes
Resource Counter (initial value: N)
- Semaphores controlling access to N (multiple) resources, thus assuming a range of non-negative values, are frequently called counting semaphores.