python实现生产者消费者模型

实现一边做酱香饼一边吃酱香饼

import time
import threading
import queue


class Proceducer():
    def __init__(self, key, full):
        self.full = full  # 最多生产full个酱香饼
        self.key = key  # 酱香饼的号数

class Consumer():
    def __init__(self, name):
        self.name = name  # 顾客的号数

def producer(name):
    while True:
        if item.qsize() < name.full:  # 可以生产酱香饼
            time.sleep(2)
            name.key += 1
            item.put(name.key)
            print('酱香饼%d号生产出来了!现在有%d个酱香饼!' % (name.key, item.qsize()))

def consumer(name):
    while True:
        if not item.empty():  # 可以购买酱香饼
            time.sleep(7)  #购买时间可以自己调整
            key = item.get()
            print('酱香饼%d号被%s购买了!现在有%d个酱香饼!' % (key, name.name, item.qsize()))


threadLock = threading.Lock()
item = queue.Queue()
p = Proceducer(0, 10)
c1 = Consumer('一号顾客')
c2 = Consumer('二号顾客')
c3 = Consumer('三号顾客')

threading1 = threading.Thread(target=producer, args=(p,))
threading2 = threading.Thread(target=consumer, args=(c1,))
threading3 = threading.Thread(target=consumer, args=(c2,))
threading4 = threading.Thread(target=consumer, args=(c3,))


threading1.start()
threading2.start()
threading3.start()
threading4.start()

结果:
当每七秒就有顾客购买时:
在这里插入图片描述
当每两秒就有顾客购买时:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值