Counting Semaphores

When you create a semaphore, you specify its initial value ‘n’. There are two main uses for a counting semaphore:

 

1.    Resource Management. The semaphore value ‘n’ represents the number of resources available. For example, the number of checkout registers in a store. When a resource is used, e.g. when a customer goes to a checkout register (corresponding to the wait operation), the semaphore value is decreased by one. When a customer finishes with checkout, then the semaphore value is increased by one, (corresponding to the signal operation). When all resources are in use and thus the semaphore is 0, then other customers wishing to check out must wait until a checkout register becomes available.

In this scenario, the semaphore should be created with an initial value of n, equal to the maximum number of resources available.

2.    Event counting. The semaphore value ‘n’ represents the number of events to be processed; for example, the number of customers queuing at a particular checkout register. When a customer enters the queue (an event occurring), the semaphore value increases by one. When the next customer is being serviced (an event being processed), then the semaphore value decreases by one.

In this scenario, the semaphore should be created with an initial value of 0.