Oriental Institute of Science and Technology, Bhopal
RGPV/CSE-6 Sem/Code:6002/Subject: Principle of Programming Language/eNotes:Unit-4
Computer Science & Engg Dept Page 9
Semaphores
Semaphore is a synchronization tool.
semaphore is a value that indicates the status of common resources.
A semaphore, in its most basic form, is a protected integer variable that can
facilitate and restrict access to shared resources in a multi-processing
environment.
The two most common kinds of semaphores are counting semaphores and
binary semaphores.
Counting semaphores represent multiple resources, while binary semaphores,
as the name implies, represents two possible states (generally 0 or 1; locked or
unlocked). Semaphores were invented by the late Edsger Dijkstra.
Semaphores can be looked at as a representation of a limited number of
resources, like seating capacity at a restaurant.
If a restaurant has a capacity of 50 people and nobody is there, the semaphore
would be initialized to 50. As each person arrives at the restaurant, they cause
the seating capacity to decrease, so the semaphore in turn is decremented.
When the maximum capacity is reached, the semaphore will be at zero, and
nobody else will be able to enter the restaurant. Instead the hopeful restaurant
goers must wait until someone is done with the resource, or in this analogy,
done eating. When a patron leaves, the semaphore is incremented and the
resource becomes available again.
A semaphore can only be accessed using the following operations: wait() and
signal(). wait() is called when a process wants access to a resource. This would
be equivalent to the arriving customer trying to get an open table.
If there is an open table, or the semaphore is greater than zero, then he can take
that resource and sit at the table. If there is no open table and the semaphore is
zero, that process must wait until it becomes available. signal() is called when a
process is done using a resource, or when the patron is finished with his meal.
The following is an implementation of this counting semaphore (where the
value can be greater than 1):