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
Python基础:多线程下的条件锁(Condition)实现生产者消费者模式,搞懂线程之间的通讯
最新推荐文章于 2023-11-01 21:42:08 发布
本文通过一个羊肉串生产与消费的场景,演示了如何使用Python的threading.Condition来实现多线程间的同步。生产者和消费者分别代表羊肉串的生产与消费过程,当生产者生产羊肉串到一定数量时,会通知所有等待的消费者进行消费,反之亦然。
1835

被折叠的 条评论
为什么被折叠?



