蒸包子

本文通过Python的多线程技术模拟了一个厨师蒸包子和多个顾客依次吃包子的过程。使用了threading模块中的Condition条件变量来实现线程间的同步与等待通知机制,确保包子被蒸好之后顾客才能开始吃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import threading,time
zhenglong=[]
zheng_lock=threading.Lock()
W=threading.Condition(lock=zheng_lock)
chi_lock=threading.Lock()
E=threading.Condition(lock=chi_lock)
def zheng(name):
    while True:
         E.acquire()
         if zhenglong.__len__()==0:
             for i in range(1,11):
                zhenglong.append(i)
                time.sleep(0.3)
                print('{0}正在蒸第{1}个包子'.format(name,i))
             print('包子蒸完了,唤醒吃货')
             E.notify_all()
         E.release()
         W.acquire()
         W.wait()
         W.release()
threading._start_new_thread(zheng,('厨师',))
def chihuo(name):
    while True:
        E.acquire()
        global zhenglong
        if zhenglong.__len__()==0:
            W.acquire()
            W.notify_all()
            W.release()
            E.wait()
        else:
            s=zhenglong.pop()
            print('{0}正在吃{1}个包子,剩余{2}个包子'.format(name,s,zhenglong.__len__()))
            time.sleep(0.1)
        E.release()
threading._start_new_thread(chihuo,('小刚',))
threading._start_new_thread(chihuo,('小明',))
threading._start_new_thread(chihuo,('小hong',))
input()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值