python---基于缓冲区的生产者消费者模型

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)

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值