# L-27 MCS 275 Mon 17 Mar 2008 : class producer

# Illustration of producer/consumer with threads.
# An object of the class Producer is a thread that
# will append to a queue consecutive integers in
# a given range and at a given pace.

import threading
import random
import time

class Producer(threading.Thread):
   """
   Appends integers to a queue.
   """
   def __init__(self,t,q,a,b,p):
      """
      Thread t to add integers in [a,b] to q,
      sleeping between 1 and p seconds.
      """
      threading.Thread.__init__(self,name=t)
      self.queue = q
      self.begin = a
      self.end = b
      self.pace = p

   def run(self):
      "produces integers at some pace"
      print self.getName() + " starts..."
      for i in range(self.begin,self.end+1):
         r = random.randint(1,self.pace)
         print self.getName() + \
             " sleeps %d seconds" % r
         time.sleep(r)
         print "appending %d to queue" % i
         self.queue.append(i)
      print "production terminated"
