Producer/Consumer Relationships
Home ] Up ] [ Producer/Consumer Relationships ] Conditions ] A Producer/Consumer Example ]

 

 

A producer/consumer relationship is a very common relationship among threads. In this kind of a relationship, the Producer thread is responsible for producing something (in this case, work), and the Consumer thread is responsible for consuming it (in this case performing the work). Note:

  • The Producer produces something and notifies the Consumer that its available.
  • The Consumer can't do anything until it's given something to consume, so it must wait until there is something available.

The typical pseudo-code for a Producer is:

enter synchronized code
  produce data
  notify consumer
leave synchronized code

while the typical pseudo-code for a Consumer is:

enter synchronized code
  while there is no data available
    wait
  consume data
leave synchronized code

In theory, the Producer could produce things as fast as it can, regardless of whether the Consumer can keep up. In the real world, to avoid running out of resources, the Producer shouldn't produce anything at a rate the the Consumer can't match. For example, it is common for data to be passed from a Producer to a Consumer by means of a shared buffer. If the buffer fills up, then the Producer shouldn't attempt to continue using that buffer, but should wait for room to become available in the buffer.

 

The page was last updated February 19, 2008