fndemers

Untitled

Jan 24th, 2021
992
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, max):
  10.       threading.Thread.__init__( self, name = threadName )
  11.       self.sharedObject = queue
  12.       self.max = max
  13.  
  14.    def run( self ):
  15.       for i in range( 11, 21 ):
  16.          time.sleep( random.randrange( 4 ) )
  17.          print ("%s adding %s to queue" % ( self.getName(), i ))
  18.          self.max.acquire()
  19.          self.sharedObject.append( i )
  20.  
  21.       print (self.getName(), "finished producing values")
  22.       print ("Terminating", self.getName())
  23.  
  24. class ConsumeFromQueue( threading.Thread ):
  25.    def __init__( self, threadName, queue, sem, max):
  26.       threading.Thread.__init__( self, name = threadName )
  27.       self.sharedObject = queue
  28.       self.max = max
  29.  
  30.    def run( self ):
  31.       sum = 0
  32.       current = 10
  33.  
  34.       for i in range( 10 ):
  35.          time.sleep( random.randrange( 3 ) )
  36.          print ("%s attempting to read %s..." % ( self.getName(), current + 1 ))
  37.          current = self.sharedObject.pop(0)
  38.          self.max.release()
  39.          print ("%s read %s" % ( self.getName(), current ))
  40.          sum += current
  41.  
  42.       print ("%s retrieved values totaling: %d" % ( self.getName(), sum ))
  43.       print ("Terminating", self.getName())
  44.  
  45. queue = []
  46.  
  47. max = threading.Semaphore(10)
  48.  
  49.  
  50. producer = ProduceToQueue( "Producer", queue, max )
  51. consumer = ConsumeFromQueue( "Consumer", queue, max )
  52.  
  53. consumer.start()
  54. producer.start()
  55.  
  56. producer.join()
  57. consumer.join()
  58.  
RAW Paste Data