Python基础:多线程下的条件锁(Condition)实现生产者消费者模式,搞懂线程之间的通讯

本文通过一个羊肉串生产与消费的场景,演示了如何使用Python的threading.Condition来实现多线程间的同步。生产者和消费者分别代表羊肉串的生产与消费过程,当生产者生产羊肉串到一定数量时,会通知所有等待的消费者进行消费,反之亦然。
import threading
import time
condtion = threading.Condition()
sheep = ['1吨羊肉串','1吨羊肉串','1吨羊肉串','1吨羊肉串','1吨羊肉串'] # 做大的长度是10,10吨羊肉

# 厂商 多个加工厂
class Producer(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)
        pass

    def run(self):
        global condtion, sheep
        while True:
            time.sleep(0.1)
            condtion.acquire()
            if len(sheep) < 10:
                # 开始生产羊肉串
                print(self.name + "生产了1吨羊肉串")
                sheep.append('1吨羊肉串')
                condtion.notifyAll()
                pass
            else:
                print("仓库满了,别生产了,放不下!")
                condtion.wait()
                pass
            condtion.release()
        pass

    pass

# 买家
class Customer(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)
        pass

    def run(self):
        global condtion, sheep
        while True:
            time.sleep(0.1)
            condtion.acquire()
            if len(sheep) > 0:
                meat = sheep.pop()
                print(self.name + "购买了" + meat + "还剩多少" + str(len(sheep)) + "吨")
                condtion.notifyAll()
                pass
            else:
                print("买光了,等厂家生产了再去买")
                condtion.wait()
                pass
            condtion.release()
        pass
    pass

if __name__ == "__main__":
    p1 = Producer("呼伦贝尔1生产场")
    p2 = Producer("呼伦贝尔2生产场")
    p3 = Producer("呼伦贝尔3生产场")
    p4 = Producer("呼伦贝尔4生产场")
    p5 = Producer("呼伦贝尔5生产场")
    p6 = Producer("呼伦贝尔6生产场")
    p1.start()
    p2.start()
    p4.start()
    p5.start()
    p6.start()

    c1 = Customer('马云')
    c2 = Customer('小马哥')
    c3 = Customer('雷布斯')
    c4 = Customer('小沈阳')
    c5 = Customer('迪丽热巴')

    c1.start()
    c2.start()
    c3.start()
    # c4.start()
    # c5.start()

    pass
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值