Thus, the semaphore is a counter that stores wakeups for future use. A semaphore cannot be accessed by more than one process at the same time. Figure 6-28 shows how the race condition can be eliminated using semaphores. When the two processes start, the consumer is halted in C1, because the initial value of filled is 0. It hen inserts the prime into the buffer and calls up on filled, thus waking up the consumer.
Lets reexamine the race condition.
Then it takes the last number out of the buffer, ups available to 100, prints the number, and returns to C1. Just before it can call down on filled, the producer gets to line P5. The rpoducer is about to up it, and the consumer is about to call down. If the consumer goes first, it will be suspended and then released right after the producer calls up. On the other hand, if the producer goes first, it will set filled to 1, and the consumer will not be suspended.