忧郁的大能猫
好奇的探索者,理性的思考者,踏实的行动者。
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对象
event = threading.Event()
# 创建并启动工作线程
thread = threading.Thread(target=worker, args=(event,))
thread.start()
print("Main thread is sleeping for 3 seconds.")
time.sleep(3) # 主线程休眠3秒钟
print("Main thread has slept for 3 seconds and is now setting event.")
event.set() # 设置事件
# 等待工作线程结束
thread.join()
print("Main thread has joined worker thread.")