Advertisement
TorroesPrime

Untitled

Aug 3rd, 2022
1,276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | None | 0 0
  1. """
  2. Name
  3. Class
  4. Project 10
  5. Date
  6. File: producerconsumer.py
  7. Producer-consumer demo with no synchronization.
  8. Producer and consumer both access shared data a given number
  9. of times. They sleep a random interval before each access.
  10. The data must be produced before it is consumed, and be produced
  11. and consumed just once.
  12. However, on some runs, the producer and consumer may access the
  13. data out of order.
  14. """
  15. import time, random
  16. from threading import Thread, current_thread, Condition
  17.  
  18. class SharedCell(object):
  19.     """Shared data that sequences writing before reading."""
  20.    
  21.     def __init__(self):
  22.         """Can produce but not consume at startup."""
  23.         self.data = -1
  24.         self.writeable = True
  25.         self.condition = Condition()
  26.        
  27.     def setData(self, data):
  28.         """Second caller must wait until someone has consumed the data before resetting it."""
  29.         self.condition.acquire()
  30.         while not self.writeable:
  31.             self.condition.wait()
  32.         print("\n%s setting data to %d" % \
  33.               (current_thread().name, data))
  34.         self.data = data
  35.         self.writeable = False
  36.         self.condition.notify()
  37.         self.condition.release()
  38.        
  39.     def getData(self):
  40.         """Caller must wait until someone has produced the data before accessing it."""
  41.         self.condition.acquire()
  42.         while self.writeable:
  43.             self.condition.wait()
  44.         print("\n%s accessing data %d" % \
  45.               (current_thread().name, self.data))
  46.         self.writeable = True
  47.         self.condition.notify()
  48.         self.condition.release()
  49.         return self.data
  50.    
  51. class Producer(Thread):
  52.     """A producer of data in a shared cell."""
  53.          
  54.     def __init__(self, cell, accessCount, sleepMax, number_of_cons):
  55.         """Create a producer with the given shared cell,
  56.        number of accesses, and maximum sleep interval."""
  57.         Thread.__init__(self, name = "Producer")
  58.         self.accessCount = accessCount
  59.         self.cell = cell
  60.         self.sleepMax = sleepMax
  61.         self.number_of_consumers = number_of_cons
  62.        
  63.     def run(self):
  64.         """"Announce start-up, sleep and write to shared
  65.        cell the given number of times, and announce
  66.        completion."""
  67.         print("\n%s starting up " % self.name)
  68.         for count in range(self.accessCount):
  69.             consumer_count = 0
  70.             time.sleep(random.randint(1, self.sleepMax))
  71.             while consumer_count <= self.number_of_consumers:
  72.                 self.cell.setData(count + 1)
  73.                 consumer_count = consumer_count+1
  74.         print("\n%s is done producing" % self.getName())
  75.        
  76. class Consumer(Thread):
  77.     """A consumer of data in a shared cell."""
  78.     global conCount
  79.     conCount = 0
  80.    
  81.     def __init__(self, cell, accessCount, sleepMax):
  82.         """Create a consumer with the given shared cell,
  83.        number of accesses, and maximum sleep interval."""
  84.         global conCount
  85.         conCount = conCount+1
  86.         Thread.__init__(self, name = "Consumer_"+str(conCount))
  87.         self.accessCount = accessCount
  88.         self.cell = cell
  89.         self.sleepMax = sleepMax
  90.         self.value = None
  91.        
  92.     def run(self):
  93.         """Announce start-up, sleep and write to shared
  94.        cell the given number of times, and announce
  95.        completion."""
  96.         print("\n%s starting up" % self.name)
  97.         for count in range(self.accessCount):
  98.             time.sleep(random.randint(1, self.sleepMax))
  99.             while self.value == self.cell.getData:
  100.                 time.sleep(random.randint(1, self.sleepMax))
  101.             self.value = self.cell.getData()
  102.         print("\n%s is done consuming" % self.name)
  103.        
  104. def main():
  105.     accessCount = int(input("Enter the number of accesses: "))
  106.     conCount = int(input("Enter the number of consumers: "))
  107.     sleepMax = 4
  108.     cell = SharedCell()
  109.     consumers = []
  110.     p = Producer(cell, accessCount, sleepMax, conCount)
  111.     consumers = []
  112.     for consumer in range(conCount):
  113.         consumers.append(Consumer(cell, accessCount, sleepMax))
  114.     print("Starting the threads")
  115.     for consumer in consumers:
  116.         print(consumer.name)
  117.     p.start()
  118.     for consumer in consumers:
  119.         consumer.start()
  120. main()
  121.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement