# L-35 MCS 260 Fri 8 Apr 2016 : class_consumer.py
"""
Illustration of producer/consumer with threads.
An object of the class Consumer is a thread that
will pop integers from the queue and print them,
at a given pace.
"""
from threading import Thread
from random import randint
from time import sleep

class Consumer(Thread):
    """
    Pops integers from a queue.
    """
    def __init__(self, t, q, n, p):
        """
        Thread t to pop n integers from q.
        """
        Thread.__init__(self, name=t)
        self.queue = q
        self.amount = n
        self.pace = p

    def run(self):
        """
        Pops integers at some pace.
        """
        print("consumption starts...")
        for i in range(0, self.amount):
            rnd = randint(1, self.pace)
            print(self.getName() + \
                " sleeps %d seconds" % rnd)
            sleep(rnd)
            while True:
                try:
                    i = self.queue.pop(0)
                    print("popped %d from queue" % i)
                    break
                except IndexError:
                    print("wait a second...")
                    sleep(1)
        print("consumption terminated")

def main():
    """
    Simulates consumption on some queue.
    """
    que = list(range(5))
    cns = Consumer('consumer', que, 5, 10)
    cns.start()
    cns.join()

if __name__ == "__main__":
    main()
