.. _producer_consumer: .. _bounded_buffer: Bounded Buffer (Producers and Consumers) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. sidebar:: Application A pipe or other finite queue (buffer), is an example of the bounded buffer problem. This problem is also called the **Producers and Consumers** problem. A finite supply of containers is available. Producers take an empty container and fill it with a product. Consumers take a full container, consume the product and leave an empty container. The main complexity of this problem is that we must maintain the count for both the number of empty and full containers that are available. .. figure:: bounded_buff.png :align: center Producers produce a product and consumers consume the product, but both use of one of the containers each time. Here is a solution to the bounded buffer problem with N containers using a :term:`monitor`:: import threading class Pool(Object): def __init__(self, start): self.items = start self.monitor = threading.Condition() def get(self): self.monitor.acquire() while( self.items == 0 ): self.monitor.wait() self.items -= 1 self.monitor.release() def put(self): self.monitor.acquire() self.items += 1 self.monitor.notify() self.monitor.release() def producer(): global full global empty while True: empty.get() # # Fill the container with product # full.put() def consumer(): global full global empty while True: full.get() # # Consume the product from the container # empty.put() # # The global code: # full = Pool(0) empty = Pool(N) # # Now create and start the desired number of producer # and consumer threads. #