如何知道threading.Condition.wait(timeout)是否已经超时或者已经通知?

How to know if threading.Condition.wait(timeout) has timed out or has been notified?

我正在开发一个包含一些线程的应用程序,每个线程 运行 都是一个有时间休眠的无限循环。我想要的是在主要线程完成后完成所有线程,这里是一个例子:

def main():

    display_res_stop = threading.Condition()
    display_result_t = threading.Thread(target=sample_t, args=(display_res_stop, ))
    display_result_t.start()

    time.sleep(4)

    display_res_stop.acquire()
    display_res_stop.notify()
    display_res_stop.release()


def sample_t(stop_cond):
    stop_cond.acquire()

    while True:
        print 5
        c = stop_cond.wait(10)

    stop_cond.release()

if __name__ == '__main__':
    main()

这个解决方案的问题是我不知道 condition.wait 是否已经完成,因为超时或因为已被通知。在第二种情况下,while 循环应该结束。

起初我在做 time.sleep(t) 并使用线程事件,但应用程序必须等到所有线程上的 t 都已通过。

我正在考虑使用 threading.Condition 和事件的混合解决方案,但我不知道这是否是最好的做法('sleep' 和事件在 True 时替换的条件) .

最简单的方法是使用 Python 3.2 或更高版本,或者将当前 threading 的 backport 移植到 3.1/2.7/etc。来自 PyPI,或者只是从 3.4's source.

复制该方法的代码

作为 Condition.wait 的文档解释:

The return value is True unless a given timeout expired, in which case it is False.

Changed in version 3.2: Previously, the method always returned None.


附带说明一下,我不确定您是否需要 Condition;您没有检查循环内的标志,也没有做任何其他容易受到竞争条件影响的事情,您只是在等待通知。这意味着,只要您不需要神奇的自动重置,Event 就可以了。 Event.wait 自 2.7/3.1+ 以来就有了 True/False return,而不是 3.2+。

毕竟这很简单,我只是专注于错误的事情:我只需要一个可以通过事件停止的睡眠,这就是 Event.wait(t) 所做的。那么这个问题,只要用事件就可以解决。

import threading
import time

def sample_thread(stop_ev):
    while not stop_ev.is_set():
        print 'Thread iteration'
        stop_ev.wait(0.1)

def main():
    stop_ev = threading.Event()
    sample_t = threading.Thread(target=sample_thread, args=(stop_ev, ))
    sample_t.start()

    # Other stuff here, sleep is just dummy
    time.sleep(14)

    stop_ev.set()

    print 'End reached.'

if __name__ == '__main__':
    main()