python threading:Event.set()会真正通知每个等待的线程

时间:2011-06-06 16:19:04

标签: python multithreading events wait

如果我有一个threading.Event和以下两行代码......

event.set()
event.clear()

...我有一些线程在等待那个事件。

我的问题与调用set()方法时会发生什么有关:

  • 我可以绝对确定所有等待的线程都会收到通知吗? (即Event.set()“通知”线程)
  • 或者可能会发生这两行在彼此之后如此快速地执行,某些线程可能仍在等待? (即Event.wait()轮询事件的状态,该状态可能已经“清除”了)

感谢您的回答!

3 个答案:

答案 0 :(得分:13)

很容易验证事情是否按预期工作:

import threading

e = threading.Event()
threads = []

def runner():
    tname = threading.current_thread().name
    print 'Thread waiting for event: %s' % tname
    e.wait()
    print 'Thread got event: %s' % tname

for t in range(100):
    t = threading.Thread(target=runner)
    threads.append(t)
    t.start()

raw_input('Press enter to set and clear the event:')
e.set()
e.clear()
for t in threads:
    t.join()
print 'All done.'

如果您运行上面的脚本并且它终止,那么一切都应该很好:-)请注意,有一百个线程正在等待设置事件;它立即设置并清除;所有线程都应该看到这个并且应该终止(虽然不是以任何明确的顺序,并且“全部完成”可以在“按Enter”提示后的任何地方打印,而不仅仅是在最后。

答案 1 :(得分:11)

在Python的内部,使用Condition()对象实现了一个事件。

调用event.set()方法时,调用条件的notify_all()(在获取锁定以确保不被中断之后),然后所有线程都会收到通知(锁定被释放)只有当通知所有线程时,才能确保所有线程都能得到有效通知。

现在,在通知之后清除事件不是问题....直到您不想使用event.is_set()检查等待线程中的事件值,但您只需要这种检查如果你等待超时。

示例:

有效的伪代码:

#in main thread
event = Event()
thread1(event)
thread2(event)
...
event.set()
event.clear()

#in thread code
...
event.wait()
#do the stuff

可能不起作用的伪代码:

#in main thread
event = Event()
thread1(event)
thread2(event)
...
event.set()
event.clear()

#in thread code
...
while not event.is_set():
   event.wait(timeout_value)
#do the stuff

编辑:在python> = 2.7中,您仍然可以等待超时的事件,并确保事件的状态:

event_state = event.wait(timeout)
while not event_state:
    event_state = event.wait(timeout)

答案 2 :(得分:0)

Python 3 +

更容易检查其是否有效

import threading
import time

lock = threading.Lock() # just to sync printing
e = threading.Event()
threads = []

def runner():
    tname = threading.current_thread().name
    with lock:
        print('Thread waiting for event ', tname)
    e.wait()
    with lock:
        print('Thread got event: ', tname)

for t in range(8): # Create 8 threads could be 100's
    t = threading.Thread(target=runner)
    threads.append(t)
    t.start()

time.sleep(1) # force wait until set/clear
e.set()
e.clear()
for t in threads:
    t.join()    
    
print('Done')
相关问题