The Producer/Consumer (Bounded Buffer) Problem

Remember the producer/consumer problem from the previous chapter? Let's try to solve it with semaphores!

We'll cover the following

The next problem we will confront in this chapter is known as the producer/consumer problem, or sometimes as the bounded buffer problem“Information Streams Sharing a Finite Buffer” by E.W. Dijkstra. Information Processing Letters 1, 1972. http://www.cs.utexas.edu/users/EWD/ewd03xx/EWD329.PDF. Did Dijkstra invent everything? No, but maybe close. He certainly was the first to clearly write down what the problems were in concurrent code. However, practitioners in OS design knew of many of the problems described by Dijkstra, so perhaps giving him too much credit would be a misrepresentation.. This problem is described in detail in the previous chapter on condition variables; see here for details.

First attempt

Our first attempt at solving the problem introduces two semaphores, empty and full, which the threads will use to indicate when a buffer entry has been emptied or filled, respectively. The code for the put and get routines is given below:

Get hands-on with 1200+ tech skills courses.