Python 事件驱动:两个线程使用事件通知交互的示例
下面是一个使用 Python 的事件驱动的例子,其中有两个线程通过事件通知相互交互:
import threading
import time
from queue import Queue
# 创建一个事件对象
event = threading.Event()
# 创建一个队列对象
queue = Queue()
# 定义一个线程 A,用于触发事件
def thread_a():
print('Thread A is waiting for event to be set')
event.wait() # 等待事件被设置
print('Thread A received event notification')
queue.put('Hello from Thread A')
# 定义一个线程 B,用于等待事件并处理
def thread_b():
print('Thread B is waiting for event to be set')
event.wait() # 等待事件被设置
print('Thread B received event notification')
message = queue.get()
print('Thread B received message:', message)
# 启动线程 A 和线程 B
thread_a = threading.Thread(target=thread_a)
thread_b = threading.Thread(target=thread_b)
thread_a.start()
thread_b.start()
# 休眠一段时间后设置事件
time.sleep(2)
event.set()
# 等待线程 A 和线程 B 完成
thread_a.join()
thread_b.join()
在这个例子中,线程 A 等待事件的设置,而线程 B 等待事件的设置和处理队列中的消息。在主线程中,我们休眠了 2 秒钟后设置了事件。这将导致线程 A 和线程 B 被唤醒,并进行相应的操作。
输出结果可能是:
Thread A is waiting for event to be set
Thread B is waiting for event to be set
Thread B received event notification
Thread A received event notification
Thread B received message: Hello from Thread A
这个例子展示了两个线程通过事件通知和队列来交互的基本原理。线程 A 等待事件被设置,当事件被设置后,它向队列中放入一个消息。线程 B 等待事件被设置,当事件被设置后,它从队列中获取消息并进行处理。
原文地址: https://www.cveoy.top/t/topic/qChI 著作权归作者所有。请勿转载和采集!