前言:十一国庆只能待在家的吴师傅十分无聊,决定开一家Python面包店打发下时间。后面的每一天,吴师傅都会用一段代码简单实现卖面包的功能,并且解决前一天暴露的问题。
为了排查顾客下了单但是没有拿到面包的问题,吴师傅要求每位面包师傅根据订单号生产面包,并且面包按订单号给到对应顾客。
"""每个面包师傅根据订单数生产面包,并且面包要按订单号给到顾客。"""
import time
import threading
import multiprocessing
import random
import zmq
PRODUCER_NUM = 3
def order(topic, order_id, pub_socket):
"""下单。"""
print('Order:%s, topic:%s' % (order_id, topic))
pub_socket.send_multipart([topic.encode(), order_id.encode()])
def worker(topic, context):
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) # 设置接受超时
print('Windows:', topic)
while 1:
msg = None
try:
msg, order_id = sub_socket.recv_multipart()
except Exception as e:
pass
else:
if msg:
# 师傅收到订单,制作完成并返回了面包
print('Finished: %s, %s' % (order_id.decode(), msg.decode()))
time.sleep(1)
def run_bakery():
context = zmq.Context()
workers = []
for i in range(PRODUCER_NUM):
# 每个师傅对应一条买面包店队伍
topic = 'P:%s' % i
w = threading.Thread(target=worker, args=(topic, context))
workers.append(w)
w.start()
for w in workers:
w.join()
def run_customer():
# 模拟顾客订单
context = zmq.Context()
pub_socket = context.socket(zmq.PUB)
pub_socket.bind("tcp://*:5555")
time.sleep(2)
orders_num = random.randint(6, 10)
for j in range(orders_num):
i = random.randint(0, PRODUCER_NUM-1)
topic = 'P:%s' % i
order_id = "id_%s" % j
time.sleep(0.1)
order(topic, order_id, pub_socket)
def run():
p1 = multiprocessing.Process(target=run_bakery)
p2 = multiprocessing.Process(target=run_customer)
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == "__main__":
run()
国庆结束了,吴师傅的面包店还会继续开下去吗?
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。