约 1365 字
约 7 分钟
条件变量(Condition Variable) 是操作系统和并发编程中的一种同步机制,用于线程/进程间的协调通信。 它允许线程在特定条件不满足时主动等待,直到其他线程通知条件可能已发生变化。
在 Python 中使用 threading
模块的 Condition
类创建条件变量,可以通过 wait
方法等待通知,notify
方法发送通知。
条件变量包含一个锁,在创建条件变量时可以通过参数传递这个锁,如果没有则会自动创建一个可重入锁。
可以通过 acquire
方法加锁,release
方法解锁,可以使用 with
语句。
下面是一个示例,consumer
线程需要等待 count
变成 10 再继续运行:
from threading import Thread, Condition
count:int = 0
cond = Condition()
def consumer():
global count
while True:
with cond: # 加锁保护 count
print('consumer')
cond.wait() # 原子地解锁并阻塞等待通知,收到通知后自动加锁
if (count == 10): # 检查 count 的值
print(count)
break
def producer():
global count
while True:
with cond: # 加锁保护 count
print('producer')
count += 1 # count 加一
cond.notify() # 发送通知
if (count == 10): # 结束
break
t1 = Thread(target=consumer) # 创建线程
t2 = Thread(target=producer)
t1.start() # 启动线程
t2.start()
t1.join() # 等待线程结束
t2.join()
创建于 2025/5/13 15:51:48
更新于 2025/5/13 15:51:48