Multiple threads producing/consuming values. : Producer Consumer : Thread PYTHON TUTORIALS


PYTHON TUTORIALS » Thread » Producer Consumer »

 

Multiple threads producing/consuming values.


from Queue import Queue

import threading
import random
import time

class ProduceToQueuethreading.Thread ):
   def __init__self, threadName, queue ):
      threading.Thread.__init__self, name = threadName )
      self.sharedObject = queue
      
   def runself ):
      for i in range1121 ):
         time.sleeprandom.randrange) )
         print "%s adding %s to queue" self.getName(), i )
         self.sharedObject.put)

      print self.getName()"finished producing values"
      print "Terminating", self.getName()

class ConsumeFromQueuethreading.Thread ):
   def __init__self, threadName, queue ):
      threading.Thread.__init__self, name = threadName )
      self.sharedObject = queue

   def runself ):
      sum = 0
      current = 10

      for i in range10 ):
         time.sleeprandom.randrange) )
         print "%s attempting to read %s..." self.getName(), current + )
         current = self.sharedObject.get()
         print "%s read %s" self.getName(), current )
         sum += current

      print "%s retrieved values totaling: %d" self.getName(), sum )
      print "Terminating", self.getName()

queue = Queue()
producer = ProduceToQueue"Producer", queue )
consumer = ConsumeFromQueue"Consumer", queue )

producer.start()
consumer.start()

producer.join()
consumer.join()



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .


PYTHON TUTORIALS

 Navioo Thread
» Producer Consumer