import random
import time
# 缓冲区列表, 存放生产的所有包子,工作方式是队列的工作方式(FIFO-first in firest out).
cacheList = []
# 如果缓冲区列表的长度为5, 缓冲区就满了, 生产者不能再生产了.
cacheListLen = 5
def isfull():
# 缓冲区满了
return len(cacheList) == 5
def consumer(name):
"""消费者"""
print("%s准备买包子......." %(name))
while True:
kind = yield
print("%s购买%s包子成功..." %(name, kind))
def producer(name):
print("%s厨师正在生产包子......." %(name))
kinds = ['A', 'B', 'C', 'D']
while True:
if not isfull():
# 模拟生产数据耗费的时间
time.sleep(random.random())
kind = random.choice(kinds)
print("%s已经生产好%s包子了..." %(name, kind))
cacheList.append(kind)
else:
print("已经有足够的包子")
yield
p = producer("hello")
next(p)
consumers = [consumer('user'+str(i)) for i in range(10)]
for i in consumers:
if not cacheList:
print("目前没有包子")
else:
# 如果缓冲区没有满, 就让生产者继续生产包子, 丛上次停止的地方继续执行.
if not isfull():
next(p)
# 从缓冲区拿出包子给消费者.
kind = cacheList.pop()
next(i)
i.send(kind)
python---基于缓冲区的生产者消费者模型
最新推荐文章于 2023-01-09 09:49:09 发布