Threads and Concurrent Programming
14.6 CASE STUDY: Cooperating Threads
For some applications it is necessary to synchronize and coordinate the
behavior of threads to enable them to carry out a cooperative task. Many
cooperative applications are based on the producer/consumer model. According to this model, two threads cooperate at producing and consuming
a particular resource or piece of data. The producer thread creates some
message or result, and the consumer thread reads or uses the result. The
consumer has to wait for a result to be produced, and the producer has to
take care not to overwrite a result that hasn’t yet been consumed. Many
types of coordination problems fit the producer/consumer model.
One example of an application for this model would be to control the
display of data that is read by your browser. As information arrives from the Internet, it is written to a buffer by the producer thread. A separate consumer thread reads information from the buffer and displays it
in your browser window. Obviously, the two threads must be carefully
synchronized.