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 .
Customers love each other , Master Wu assigns an exclusive sales window to each master , In this way, customers can go to a specific window to buy the bread they want .
""" Master Wu assigned a special sales window to each master , Customers can buy the desired bread at the window where they like the master .""" import time import threading import random import zmq TOTAL = [] END_FLAG = False PRODUCER_NUM = 3 CONSUMER_NUM = 3 def producer(topic, pub_socket): """ Making bread .""" num = 0 while True: time.sleep(0.2) pub_socket.send(topic.encode('utf8')) # print('Producer: I produced one:', topic) num += 1 if num >= 3: # Shifu do 3 A loaf of bread is coming off work . break def consumer(topic, context, freq): 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(freq) def run(): context = zmq.Context() pub_socket = context.socket(zmq.PUB) pub_socket.bind("tcp://*:5555") producers = [] consumers = [] for i in range(PRODUCER_NUM): # Each chef corresponds to a bakery team topic = 'P:%s' % i p = threading.Thread(target=producer, args=(topic, pub_socket)) producers.append(p) p.start() c = threading.Thread(target=consumer, args=(topic, context, i)) consumers.append(c) c.start() for p in producers: p.join() global END_FLAG END_FLAG = True # close the door , Customer consumption should also be stopped for c in consumers: c.join() if __name__ == "__main__": run()
Master Wu found that some master bread sold well , Customers often can't buy ; Some masters' bread is hard to sell , Too much to sell . Master Wu wants to change the sales mode , Improve resource utilization .