Table of Contents:

线程同步

threading.Event是一个线程同步工具,用于线程之间的事件通知和等待。

  1. 设置Event:调用set()方法可以将事件设置为已发生状态。
  2. 清除Event:调用clear()方法可以将事件设置为未发生状态。
  3. 等待Event的发生:调用wait()方法会使线程等待事件的发生,如果事件已经发生则立即返回,否则一直等待直到事件被设置或超时。
  4. 检查Event状态:调用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.")