Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time, random
- from threading import Thread, currentThread
- class SharedCell(object):
- """shared data for the producers/consumer problem."""
- def __init__(self):
- self.data = -1
- def setData(self, data):
- """producers method to write to shared data."""
- print("%s setting data to "%d %(currentThread().getName(),data))
- self.data = data
- def getData(self):
- """consumer's method to read from shared data."""
- print("%s accessing data %d"%(currentThread().getName(),self.data))
- return self.data
- class Producer(Thread):
- """Represents a producer."""
- def ___init__(self, cell, accessCount, sleepMax):
- """creates a producer with the given shared cell, number of accesses, and maximum sleep interval."""
- super().__init__(self,name="Producer")
- self.accessCount = accessCount
- self.cell = cell
- self.sleepMax = sleepMax
- def run(self):
- """announce start-up, sleep, and write to shared cell the given number of times, and announces completion."""
- print("%s starting up"%self.getName())
- for count in range(self.accessCount):
- time.sleep(random.randint(1,self.sleepMax))
- self.cell.setData(count+1)
- print("%s is done producing"%self.getName())
- class Consumer(Thread):
- """Represents a consumer"""
- conCount = 0
- def __init__(self, cell, accessCount,sleepMax):
- """Create a producer with a given shared cell, number of accesses, and maximum sleep interval."""
- conCount = conCount+1
- Thread.__init__(self, name = "Consumer_"+str(conCount))
- self.accessCount = accessCount
- self.cell = cell
- self.sleepMax = sleepMax
- def run(self):
- """Announces start-up, sleep, and read from shared cell the given number of times, and announce completion."""
- print("%s starting up "%self.getName())
- for count in range(self.accessCount):
- time.sleep(random.randint(1,self.sleepMax))
- value = self.cell.getData()
- print("%s is done consuming"%self.getName())
- def main():
- """get the number of accesses from the user, create a shared cell, and create and startup a producer and consumer"""
- accessCount = int(input("Enter the number of accesses:"))
- sleepMax = 4
- cell = SharedCell()
- producer = Producer(cell, accessCount, sleepMax)
- consumer = Consumer(cell, accessCount, sleepMax)
- print("Starting the threads")
- producer.start()
- consumer.start()
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement