– Start
点击此处观看本系列配套视频。
条件变量
from threading import Thread
from threading import Condition
# 条件变量
condition = Condition()
data = list()
def producer():
with condition:
for i in range(10):
# 此处必须是 while
while len(data) > 0:
# 如果消息没有被接收,等待被通知
condition.wait()
# 发送消息
msg = f'message {i}'
data.append(msg)
print(f'sent {msg}')
condition.notify_all()
# 发送 None,表示消息发送完毕
while len(data) > 0:
condition.wait()
data.append(None)
condition.notify_all()
return
def consumer():
while True:
with condition:
# 此处必须是 while