前言:十一国庆只能待在家的吴师傅十分无聊,决定开一家Python面包店打发下时间。后面的每一天,吴师傅都会用一段代码简单实现卖面包的功能,并且解决前一天暴露的问题。
由于昨天面包师傅抱怨一个人干活太累,吴师傅请多了两个师傅来帮忙了。
"""吴师傅请多了两个python面包师傅,工作似乎轻松了很多。"""
import time
import threading
TOTAL = 0
END_FLAG = False
PRODUCER_NUM = 3
def producer(lock):
"""生产面包。"""
num = 0
global TOTAL
while True:
time.sleep(1)
lock.acquire()
TOTAL += 1
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 > 0:
print("Consumer: I am so happy.")
lock.acquire()
TOTAL -= 1
lock.release()
else:
time.sleep(2)
print("Consumer: I am waiting!")
print("Consumer: Oh no!")
def run():
lock = threading.Lock()
producers = []
for _ in range(PRODUCER_NUM):
p = threading.Thread(target=producer, args=(lock,))
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 删除。