fndemers

Untitled

Jan 24th, 2021
962
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import threading
  5. import random
  6. import time
  7.  
  8. class ProduceToQueue( threading.Thread ):
  9.    def __init__( self, threadName, queue):
  10.       threading.Thread.__init__( self, name = threadName )
  11.       self.sharedObject = queue
  12.  
  13.    def run( self ):
  14.       for i in range( 11, 21 ):
  15.          time.sleep( random.randrange( 4 ) )
  16.          print ("%s adding %s to queue" % ( self.getName(), i ))
  17.          self.sharedObject.append( i )
  18.  
  19.       print (self.getName(), "finished producing values")
  20.       print ("Terminating", self.getName())
  21.  
  22. class ConsumeFromQueue( threading.Thread ):
  23.    def __init__( self, threadName, queue):
  24.       threading.Thread.__init__( self, name = threadName )
  25.       self.sharedObject = queue
  26.  
  27.    def run( self ):
  28.       sum = 0
  29.       current = 10
  30.  
  31.       for i in range( 10 ):
  32.          time.sleep( random.randrange( 3 ) )
  33.          print ("%s attempting to read %s..." % ( self.getName(), current + 1 ))
  34.          current = self.sharedObject.pop(0)
  35.          print ("%s read %s" % ( self.getName(), current ))
  36.          sum += current
  37.  
  38.       print ("%s retrieved values totaling: %d" % ( self.getName(), sum ))
  39.       print ("Terminating", self.getName())
  40.  
  41. queue = []
  42.  
  43. producer = ProduceToQueue( "Producer", queue )
  44. consumer = ConsumeFromQueue( "Consumer", queue )
  45.  
  46. consumer.start()
  47. producer.start()
  48.  
  49. producer.join()
  50. consumer.join()
  51.  
  52.  
  53.  
RAW Paste Data