好奇的探索者,理性的思考者,踏实的行动者。
Table of Contents:
threading.Event
是一个线程同步工具,用于线程之间的事件通知和等待。
set()
方法可以将事件设置为已发生状态。clear()
方法可以将事件设置为未发生状态。wait()
方法会使线程等待事件的发生,如果事件已经发生则立即返回,否则一直等待直到事件被设置或超时。is_set()
方法可以检查事件的当前状态,即是否已经发生。import threading
import time
def worker(event):
print("Worker thread is waiting for event.")
# 等待事件的发生
event.wait() print("Worker thread has received event and is now processing.")
print("event status is:", event.is_set())
# 清除事件
event.clear() print("event status is:", event.is_set())
# 创建Event对象
= threading.Event()
event
# 创建并启动工作线程
= threading.Thread(target=worker, args=(event,))
thread
thread.start()
print("Main thread is sleeping for 3 seconds.")
3) # 主线程休眠3秒钟
time.sleep(print("Main thread has slept for 3 seconds and is now setting event.")
set() # 设置事件
event.
# 等待工作线程结束
thread.join()
print("Main thread has joined worker thread.")