consumer.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. This module represents the Consumer.
  3. Computer Systems Architecture Course
  4. Assignment 1
  5. March 2020
  6. """
  7. from threading import Thread
  8. import time
  9. import threading
  10. class Consumer(Thread):
  11. """
  12. Class that represents a consumer.
  13. """
  14. def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
  15. """
  16. Constructor.
  17. :type carts: List
  18. :param carts: a list of add and remove operations
  19. :type marketplace: Marketplace
  20. :param marketplace: a reference to the marketplace
  21. :type retry_wait_time: Time
  22. :param retry_wait_time: the number of seconds that a producer must wait
  23. until the Marketplace becomes available
  24. :type kwargs:
  25. :param kwargs: other arguments that are passed to the Thread's __init__()
  26. """
  27. Thread.__init__(self, **kwargs)
  28. self.carts = carts
  29. self.marketplace = marketplace
  30. self.retry_wait_time = retry_wait_time
  31. def run(self):
  32. name = threading.currentThread().getName()
  33. for cart in self.carts:
  34. cart_id = self.marketplace.new_cart()
  35. for operation in cart:
  36. if operation["type"] == "add":
  37. for _ in range(operation["quantity"]):
  38. while not self.marketplace.add_to_cart(cart_id, operation["product"]):
  39. time.sleep(self.retry_wait_time)
  40. elif operation["type"] == "remove":
  41. for _ in range(operation["quantity"]):
  42. self.marketplace.remove_from_cart(cart_id, operation["product"])
  43. products = []
  44. products.append(self.marketplace.place_order(cart_id))
  45. for product in products:
  46. for item in product:
  47. print(name + " bought " + str(item))