Preface : Master Wu, who can only stay at home on the national day, is very boring , Decided to open a Python The bakery passed the time . Every day after that , Master Wu will use a piece of code to simply realize the function of selling bread , And solve the problems exposed the day before .
Master Wu decided to change the bakery to order mode , Each master produces bread according to the number of orders for his bread , This improves productivity .
""" The bakery changed to accept orders , Each Baker produces bread according to the number of orders .""" import time import threading import random import zmq END_FLAG = False PRODUCER_NUM = 3 def send_task(topic, pub_socket): """ Place an order .""" print('Order:', topic) pub_socket.send(topic.encode('utf8')) def worker(topic, context): global END_FLAG sub_socket = context.socket(zmq.SUB) sub_socket.connect("tcp://localhost:5555") sub_socket.setsockopt(zmq.SUBSCRIBE, topic.encode('utf8')) sub_socket.setsockopt(zmq.RCVTIMEO, 2000) # Set accept timeout while not END_FLAG: msg = None try: msg = sub_socket.recv() except Exception as e: pass else: if msg: print('Consumer: I had buy:', msg.decode()) time.sleep(0.1) def run(): context = zmq.Context() pub_socket = context.socket(zmq.PUB) pub_socket.bind("tcp://*:5555") workers = [] for i in range(PRODUCER_NUM): # Each chef corresponds to a bakery team topic = 'P:%s' % i w = threading.Thread(target=worker, args=(topic, context,)) workers.append(w) w.start() time.sleep(2) # Simulated customer order orders_num = random.randint(6, 10) for _ in range(orders_num): i = random.randint(0, PRODUCER_NUM-1) topic = 'P:%s' % i send_task(topic, pub_socket) time.sleep(2) END_FLAG = True for w in workers: w.join() if __name__ == "__main__": run()
Some customers reported that they placed the order but didn't get the bread , How to track the execution of each order ?