python 生产者 消费者

  一个伙夫蒸馒头(生产者),要求蒸够30个,等待,并唤醒吃馒头的人
三个吃货吃馒头(消费者),要求同时吃,当任何一个人发现没有馒头了,
就唤醒伙夫


  生产者是一堆线程,消费者是另一堆线程,内存缓冲区可以使用list数组
队列,数据类型只要定义一个简单的类就好。关键是任何处理多线程之间
的协作。这其实也是多线程通信的一个范例。


  在这个模型中,最关键就是内存缓冲区为空的时候消费者必须等待,而
内存缓冲区满的时候,生产者必须等待。其他时候可以是个动态平衡。值得
注意的是多线程对临界区资源的操作时候必须在读写中只能存在一个线程,
所以需要设计锁的策略


import  threading
import time
guo = []
class HuoFu(threading.Thread):
    def run(self):
        #生产馒头
        while True:
            condchihuo.acquire()
            if len(guo) == 0:
                for i in range(1,11):
                    guo.append(i)
                    print("伙夫生产第%d个馒头"%i)
                    time.sleep(1)
                condchihuo.notify_all()
            condchihuo.release()


class ChiHuo(threading.Thread):
    mantou = None
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name


    def run(self):
        while True:
            condchihuo.acquire()
            if len(guo) > 0:
                #吃馒头
                mantou = guo.pop()
                time.sleep(1)
            else:
                #通知伙夫
                condhuofu.acquire()
                condhuofu.notify()
                condhuofu.release()
                condchihuo.wait()
            condchihuo.release()
            if mantou is not None:
                print("%s在吃第%d个馒头"%(self.name,mantou))


lockhuofu = threading.Lock()
condhuofu = threading.Condition(lockhuofu)
lockchihuo = threading.Lock()
condchihuo = threading.Condition(lockchihuo)


huofu = HuoFu()
huofu.start()
zhangsan = ChiHuo("张三")
zhangsan.start()
lisi = ChiHuo("李四")
lisi.start()
wangwu = ChiHuo("王五")

wangwu.start()


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值