16.2.6. Event Objects
This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.
An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.
class threading.Event:
The internal flag is initially false.
实例方法:
- set()
Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.
- clear()
Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.
- wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
翻译:Event是最简单的线程间通信机制,一个线程负责给事件发信号,其他线程等待事件。
Event类内部有一个flag标识,初始值为False。
Event类常用的三个方法有:set、clear、wait。set方法会将flag标识置为True,所有处于等待的线程将会被唤醒;clear方法会将flag重置为False;wait方法将阻塞线程,除非flag标识被置为True。
演示:
# coding:gbk
import threading
import time
ev=threading.Event()
def func():
print '%s waits event...' % threading.currentThread().getName()
ev.wait()
print '%s receives event...' % threading.currentThread().getName()
if __name__ == '__main__':
t1=threading.Thread(target=func,args=())
t2=threading.Thread(target=func,args=())
t1.start()
t2.start()
time.sleep(5) #主线程休眠5秒
print 'main thread sets event...'
ev.set() #主线程设置事件
运行结果:
C:\Python27\python.exe E:/pythonproj/基础练习/t7.py
Thread-1 waits event...
Thread-2 waits event...
main thread sets event...
Thread-1 receives event...
Thread-2 receives event...
Process finished with exit code 0