python-threading.Event()

threading模块提供Event类实现线程之间的通信

threading.Event可以使一个线程等待其他线程的通知。其内置了一个标志,初始值为False。线程通过wait()方法进入等待状态,直到另一个线程调用set()方法将内置标志设置为True时,Event通知所有等待状态的线程恢复运行;调用clear()时重置为 False。还可以通过isSet()方法查询Envent对象内置状态的当前值。

Event其实就是一个简化版的 Condition。Event没有锁,无法使线程进入同步阻塞状态。

  1. isSet(): 当内置标志为True时返回True。
  2. set(): 将标志设为True,并通知所有处于等待阻塞状态的线程恢复运行状态。
  3. clear(): 将标志设为False。
  4. wait([timeout]): 如果标志为True将立即返回,否则阻塞线程至等待阻塞状态,等待其他线程调用set()。

 

import threading
import time
event = threading.Event()
def func():
    # 等待事件,进入等待阻塞状态
    print('%s wait for event...' % threading.currentThread().getName())
    event.wait()
    # 收到事件后进入运行状态
    print('%s recv event.' % threading.currentThread().getName())
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t1.start()
t2.start()

time.sleep(2)

# 发送事件通知
print('MainThread set event.')
event.set()
----------------------------------------------------
Thread-6 wait for event...Thread-7 wait for event...

MainThread set event.
Thread-6 recv event.
Thread-7 recv event.

 

posted @ 2022-10-28 15:23  小柴i  阅读(1218)  评论(0编辑  收藏  举报