producer.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """
  2. This module represents the Producer.
  3. Computer Systems Architecture Course
  4. Assignment 1
  5. March 2020
  6. """
  7. from threading import Thread
  8. import time
  9. class Producer(Thread):
  10. """
  11. Class that represents a producer.
  12. """
  13. def __init__(self, products, marketplace, republish_wait_time, **kwargs):
  14. """
  15. Constructor.
  16. @type products: List()
  17. @param products: a list of products that the producer will produce
  18. @type marketplace: Marketplace
  19. @param marketplace: a reference to the marketplace
  20. @type republish_wait_time: Time
  21. @param republish_wait_time: the number of seconds that a producer must
  22. wait until the marketplace becomes available
  23. @type kwargs:
  24. @param kwargs: other arguments that are passed to the Thread's __init__()
  25. """
  26. Thread.__init__(self, **kwargs)
  27. self.products = products
  28. self.marketplace = marketplace
  29. self.republish_wait_time = republish_wait_time
  30. def run(self):
  31. producer_id = self.marketplace.register_producer()
  32. while True:
  33. for product in self.products:
  34. new_products = []
  35. for _ in range(product[1]):
  36. new_products.append(product[0])
  37. for new_product in new_products:
  38. while not self.marketplace.publish(producer_id, new_product):
  39. time.sleep(self.republish_wait_time)
  40. time.sleep(product[2])