前言:十一国庆只能待在家的吴师傅十分无聊,决定开一家Python面包店打发下时间。后面的每一天,吴师傅都会用一段代码简单实现卖面包的功能,并且解决前一天暴露的问题。
顾客各有所爱,吴师傅为每位师傅分配一个专属售卖窗口,这样顾客就可以去特定窗口买自己想要的面包了。
"""吴师傅为每位师傅分配了专属的一个售卖窗口,客户可以在喜欢师傅的窗口买到想要的面包了。"""
import time
import threading
import random
import zmq
TOTAL = []
END_FLAG = False
PRODUCER_NUM = 3
CONSUMER_NUM = 3
def producer(topic, pub_socket):
"""生产面包。"""
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:
# 师傅做3个面包就要下班了。
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) # 设置接受超时
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):
# 每个师傅对应一条买面包店队伍
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 # 关门了,顾客消费也要停止
for c in consumers:
c.join()
if __name__ == "__main__":
run()
吴师傅发现有的师傅面包很好卖,顾客经常买不到;有的师傅面包不好卖,做多了卖不出去。吴师傅想要改变售卖模式,提升资源利用率。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。