4.3.2. Bounded Buffer (Producers and Consumers)ΒΆ

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.

../_images/bounded_buff.png

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 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.
#