# L-39 MCS 260 Wed 28 Nov 2007 : class consumer # # 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 import random import time 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): r = random.randint(1,self.pace) print self.getName() + \ " sleeps %d seconds" % r time.sleep(r) while True: try: i = self.queue.pop(0) print "popped %d from queue" % i break except IndexError: print "wait a second..." time.sleep(1) print "consumption terminated"