Python高阶--Condition
Condition条件触发
import threading
import time
class Producer(threading.Thread):
# 生产者函数
def run(self):
global count
while True:
if con.acquire():
# 当count 小于等于1000 的时候进行生产
if count > 1000:
con.wait()
else:
count = count + 100
msg = self.name + ' produce 100, count=' + str(count)
print(msg)
# 完成生成后唤醒waiting状态的线程,
# 从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁
con.notify()
con.release()
time.sleep(1)
class Consumer(threading.Thread):
# 消费者函数
def run(self):
global count
while True:
# 当count 大于等于100的时候进行消费
if con.acquire():
if count < 100:
con.wait()
else:
count = count - 3
msg = self.name + ' consume 3, count=' + str(count)
print(msg)
con.notify()
# 完成生成后唤醒waiting状态的线程,
# 从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁
con.release()
time.sleep(1)
def test():
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
if name == 'main':
count = 500
con = threading.Condition()
test()
合集:
Python基础+高阶
分类:
Python基础+高阶知识
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具