前言:十一国庆只能待在家的吴师傅十分无聊,决定开一家Python面包店打发下时间。后面的每一天,吴师傅都会用一段代码简单实现卖面包的功能,并且解决前一天暴露的问题。
昨天吴师傅多请了两位师傅,现在有三位师傅在干活了。吴师傅需要知道那位师傅的面包更受欢迎,于是要求每位师傅做的面包上都要有该师傅的标识。
"""每位师傅做的面包上面都有师傅的标示,这样吴师傅就能哪位师傅的面包更受欢迎了。"""
import time
import threading
import random
TOTAL = []
END_FLAG = False
PRODUCER_NUM = 3
def producer(lock, p_num):
"""生产面包。"""
producer_flag = 'P:%s' % p_num
num = 0
global TOTAL
while True:
time.sleep(1)
lock.acquire()
TOTAL.append(producer_flag)
lock.release()
print('Producer: I produced one.')
num += 1
if num >= 3:
# 师傅做3个面包就要下班了。
print('Done.')
break
def consumer(lock):
"""消费者,买到面包总要说点什么吧。"""
global TOTAL
global END_FLAG
while not END_FLAG:
if TOTAL:
lock.acquire()
producer_flag = TOTAL.pop()
print('Consumer: The flag is %s' % producer_flag)
choice_flag = random.choice(['P:0', 'P:1', 'P:2'])
if producer_flag != choice_flag:
print('Consumer: I don\'t want:', producer_flag)
TOTAL.append(producer_flag)
lock.release()
else:
time.sleep(2)
print("Consumer: I am waiting!")
print("Consumer: Oh no!")
def run():
lock = threading.Lock()
producers = []
for i in range(PRODUCER_NUM):
p = threading.Thread(target=producer, args=(lock, i,))
producers.append(p)
p.start()
c = threading.Thread(target=consumer, args=(lock,))
c.start()
for p in producers:
p.join()
global END_FLAG
global TOTAL
while TOTAL:
# 得等面包卖完才能关门呢。
time.sleep(1)
END_FLAG = True # 关门了,顾客消费也要停止
c.join()
if __name__ == "__main__":
run()
吴师傅发现顾客各有所爱,会买自己喜欢的师傅的面包。怎么做才能直接卖给顾客想要的面包呢?
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。