蒸馒头 import threading,time zhenglong=[] 共享数据 蒸笼 创建俩把锁 一把蒸馒头的锁 由伙夫掌管 一把吃馒头的锁 由吃货掌管 zheng_lock=threading.Lock() zheng_Cond=threading.Condition(lock=zheng_lock) chi_lock=threading.Lock() chi_Cond=threading.Condition(lock=chi_lock) class huofu(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.setName(name) def run(self): while True: chi_Cond.acquire() 被谁唤醒 if len(zhenglong)==0: 开始蒸馒头 for i in range(1,11): zhenglong.append(i) time.sleep(0.5) print(' 正在蒸第{0}个馒头'.format(i)) print('馒头蒸完 唤醒吃货门开始吃馒头...') chi_Cond.notify_all() 唤醒了吃货们 chi_Cond.release()唤醒了伙夫 他就释放 伙夫 进入休眠 zheng_Cond.acquire() zheng_Cond.wait() zheng_Cond.release() class chihuo(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.setName(name) def run(self): while True: chi_Cond.acquire() #上锁 同一时刻只有一个吃货在获取吃馒头的资源 global zhenglong if len(zhenglong)==0: 呼唤伙夫蒸馒头 只叫一次 吃货进入休眠 zheng_Cond.acquire() 锁定伙夫的线程 上锁 只允许一人叫 其他人就不访问了 zheng_Cond.notify() 唤醒伙夫 zheng_Cond.release() 释放 chi_Cond.wait() 这个吃货进入休眠 else: mantou=zhenglong.pop() print('{0}吃了第{1}个馒头 剩余{2}个馒头'.format(self.getName(),mantou,len(zhenglong))) time.sleep(0.5) chi_Cond.release() 解锁 W=huofu('伙夫') xiaogang=chihuo('小刚') xiaoming=chihuo("小明") xiaomi=chihuo('小米') W.start() xiaogang.start() xiaoming.start() xiaomi.start() 主线程不死 input()
蒸馒头的线程
最新推荐文章于 2020-03-24 22:36:35 发布