The software solution presented before only works if there is two processes competing for the same code block. Likewise, it is not real efficient if it needs to be used a lot. Semaphores are general-purpose primitives that allow solving a variety of synchronization problems in a systematic manner.
A semaphore is a non-negative integer variable that can be accessed using only two special operations, P and V.
- V(s): increment s by 1
- P(s): if s > 0, decrement s by 1, otherwise wait until s > 0
The bounded-buffer problem is a classic synchronization problem intended to illustrate process cooperation. A producer process shares a buffer with a consumer process. The buffer has a fixed number of slots. The producer fills empty slots with data in increasing order. The consumers follows the producer by removing the data in the same order. The buffer is called a circular buffer because, upon reaching the last slot, each process continues with the first slot (modulo n).
The solution must guarantee the following:
- Consumers do not overtake producers and access empty slots.
- Producers do not overtake consumers and overwrite full slots.
Using semaphores in the bounded-buffer problem
Semaphores offer a very intuitive and elegant solution to the bounded-buffer problem that satisfies the requirements that producers do not overtake consumers and vice versa.
Two semaphores are used to coordinate the processes.
The semaphore f represents the number of full buffer slots and is incremented each time the producer places a new data item into the buffer and decremented each time the consumer removes an item from the buffer.
The semaphore e represents the number of empty slots and is modified by the producer and consumer analogously.
Semaphores was originally found on Access 2 Learn