如何知道线程.条件.等待(超时)已超时或已收到通知?

2024-04-19 15:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个有一些线程的应用程序,每个线程都运行一个无限循环,有一个时间睡眠。我想要的是在主线程完成后完成所有线程,下面是一个示例:

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()

这个解决方案的问题是我不知道条件。等等已完成,因为超时或已收到通知。在第二种情况下,while循环应该结束。在

一开始我在做一个时间。睡觉(t) 并使用线程事件,但应用程序必须等到所有线程上的t都已通过。在

我在考虑混合解决方案螺纹。条件但我不知道这是否是最好的选择(条件是“sleep”和Event替换为True)。在


Tags: sample应用程序maindefdisplay时间ressleep
2条回答

实现这一点的简单方法是使用Python3.2或更高版本,或者从PyPI获取当前threading到3.1/2.7/etc.的后端端口,或者只从3.4's source复制该方法的代码。在

正如^{}的文档所解释的那样:

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的返回,而不是3.2+。在

毕竟这很简单,我只是把注意力放在了错误的事情上:我只需要一个可以被一个事件打断的睡眠,这就是为什么事件。等等(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()

相关问题 更多 >