首页 > 编程语言 > 详细

python线程condition条件锁应用实例

时间:2019-04-12 18:33:55      阅读:226      评论:0      收藏:0      [点我收藏+]
import time
import threading
# 吃火锅鱼丸
guo = []
suo = threading.Condition()  #条件锁
# 生产者负责生产
class Produce(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire() #先锁住
        while True:
            time.sleep(1)
            guo.append("鱼丸")
            print("%s生产了一个鱼丸,现在锅里有%s个鱼丸"%(self.name,len(guo)))
            if len(guo)>=5:
                print("锅里已经有%s个鱼丸"%len(guo))
                suo.notify() # 通知
                suo.wait()   # wait等待  释放另一个线程
                
# 消费者负责消费
class Consumer(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            time.sleep(1.5)
            guo.pop()
            print("%s吃了一个鱼丸,现在锅里有%s个鱼丸"%(self.name,len(guo)))
            if len(guo)<1:
                print("锅里已经没有鱼丸了,请添加鱼丸。")
                suo.notify() # 通知
                suo.wait()# wait 等待   释放另一个线程
pro = Produce()
pro.start()
con = Consumer()
con.start()

# 汽车订单变化
Car = ["保时捷911","丰田普拉多","哈弗H5","奔驰G500","路虎","法拉利","宝马X5","奥迪A8","膜拜单车","大巴车"]
suo = threading.Condition()  #条件锁
List = []
index = -1
class car(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            global index
            time.sleep(2)
            index+=1
            List.append(Car[index])
            print("恭喜靳志龙喜提一辆%s,请继续选择你喜爱的车"%Car[index])
            suo.notify()
            if len(List)>=10:
                print("对不起,你的银行卡余额不足")
                suo.release()
                break
            else:
                suo.wait()
class carbox(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        suo.acquire()
        while True:
            global index
            time.sleep(0.5)
            print("仓库里还有%s辆车"%(len(Car)-index-1))
            suo.notify()
            if len(List) >= 10:
                print("哈哈,其实我们也没有车了,小哥哥")
                suo.release()
                break
            else:
                suo.wait()
aa = car()
aa.start()
bb = carbox()
bb.start()

 

python线程condition条件锁应用实例

原文:https://www.cnblogs.com/aloneindefeat/p/10697758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!