# L-12 MCS 507 Mon 18 Sep 2023 : classconsumer.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.
"""

import threading
from random import randint
from time import sleep

class Consumer(threading.Thread):
    """
    Pops integers from a queue.
    """
    def __init__(self, t, q, n, p):
        """
        Thread t to pop n integers from q.
        """
        threading.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):
            nbr = randint(1, self.pace)
            print(self.getName() + \
                " sleeps %d seconds" % nbr)
            sleep(nbr)
            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")
