-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarketplace.py
104 lines (84 loc) · 2.98 KB
/
marketplace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""
This module represents the Marketplace.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
import threading
from tema.cart import Cart
class Marketplace:
"""
Class that represents the Marketplace. It's the central part of the implementation.
The producers and consumers use its methods concurrently.
"""
lock = threading.Lock()
producers = list()
carts = list()
products = list()
orders = list()
def __init__(self, queue_size_per_producer):
"""
Constructor
:type queue_size_per_producer: Int
:param queue_size_per_producer: the maximum size of a queue associated with each producer
"""
self.queue_size_per_producer = queue_size_per_producer
self.is_running = True
self.no_consumers = 0
def register_producer(self):
"""
Returns an id for the producer that calls this.
"""
with self.lock:
self.producers.append(len(self.producers))
return len(self.producers) - 1
def publish(self, producer_id, product):
"""
Adds the product provided by the producer to the marketplace
:type producer_id: String
:param producer_id: producer id
:type product: Product
:param product: the Product that will be published in the Marketplace
:returns True or False. If the caller receives False, it should wait and then try again.
"""
self.products.append(product)
def new_cart(self):
"""
Creates a new cart for the consumer
:returns an int representing the cart_id
"""
with self.lock:
self.carts.append(Cart(len(self.carts)))
return len(self.carts) - 1
def add_to_cart(self, cart_id, product):
"""
Adds a product to the given cart. The method returns
:type cart_id: Int
:param cart_id: id cart
:type product: Product
:param product: the product to add to cart
:returns True or False. If the caller receives False, it should wait and then try again
"""
if product in self.products:
self.products.remove(product)
self.carts[cart_id].add(product)
return True
return False
def remove_from_cart(self, cart_id, product):
"""
Removes a product from cart.
:type cart_id: Int
:param cart_id: id cart
:type product: Product
:param product: the product to remove from cart
"""
self.carts[cart_id].delete(product)
self.products.append(product)
def place_order(self, cart_id, cons_name):
"""
Return a list with all the products in the cart.
:type cart_id: Int
:param cart_id: id cart
"""
for product in self.carts[cart_id].products:
print(cons_name + " bought " + str(product))