下面是一个使用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等待事件被设置,当事件被设置后,它从队列中获取消息并进行处理

python 事件驅動 兩個綫程通過事件通知互動的例子

原文地址: http://www.cveoy.top/t/topic/iWge 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录