前言:十一国庆只能待在家的吴师傅十分无聊,决定开一家Python面包店打发下时间。后面的每一天,吴师傅都会用一段代码简单实现卖面包的功能,并且解决前一天暴露的问题。
吴师傅决定将面包店改为订单模式,每位师傅根据自己面包的订单数生产面包,这样能够提升生产效能。
"""面包店改为接受订单模式,每个面包师傅根据订单数生产面包。"""
import time
import threading
import random
import zmq
END_FLAG = False
PRODUCER_NUM = 3
def send_task(topic, pub_socket):
"""下单。"""
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) # 设置接受超时
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):
# 每个师傅对应一条买面包店队伍
topic = 'P:%s' % i
w = threading.Thread(target=worker, args=(topic, context,))
workers.append(w)
w.start()
time.sleep(2)
# 模拟顾客订单
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()
有顾客反馈自己下了单但是没有拿到面包,怎么样才能跟踪每一个订单执行情况呢?
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。