The Producer/Consumer (Bounded Buffer) Problem
This lesson introduces the famous producer/consumer problem and presents an attempt to solve it.
We'll cover the following
The next synchronization problem we will confront in this chapter is known as the producer/consumer problem, or sometimes as the bounded buffer problem,
The problem
Imagine one or more producer threads and one or more consumer threads. Producers generate data items and place them in a buffer; consumers grab said items from the buffer and consume them in some way.
This arrangement occurs in many real systems. For example, in a multi-threaded web server, a producer puts HTTP requests into a work queue (i.e., the bounded buffer). While, the consumer threads take requests out of this queue and process them.
A bounded buffer is also used when you pipe the output of one program into another, e.g., grep foo file.txt | wc -l
. This example runs two processes concurrently; grep
writes lines from file.txt
with the string foo
in them to what it thinks is standard output; the UNIX shell redirects the output to what is called a UNIX pipe (created by the pipe system call). The other end of this pipe is connected to the standard input of the process wc
, which simply counts the number of lines in the input stream and prints out the result. Thus, the grep
process is the producer; the wc
process is the consumer; between them is an in-kernel bounded buffer; you, in this example, are just the happy user.
Because the bounded buffer is a shared resource, we must, of course, require synchronized access to it,
The first thing needed is a shared buffer, into which a producer puts data, and out of which a consumer takes data. Let’s just use a single integer for simplicity (you can certainly imagine placing a pointer to a data structure into this slot instead), and the two inner routines to put a value into the shared buffer, and to get a value out of the buffer. See the code excerpt below for details.
Get hands-on with 1400+ tech skills courses.