了解thread.join(timeout) [英] Understanding thread.join(timeout)

查看:257
本文介绍了了解thread.join(timeout)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于某个线程, 超时参数应在 timeout (如果尚未终止)之后停止该线程.

So the timeout param, for a thread, should stop the thread after timeout seconds (if it hasn't terminated yet).

在我的软件中,我试图替换 Queue.Queue.join()(它包含每个线程的一个项目:每个线程都将运行Queue.Queue.task_done()),如果线程没有终止,请停止软件.因此,如果一个线程(除其他50个线程之外)没有终止,那么它将全部冻结.

In my software I'm trying to replace a Queue.Queue.join() (it contains an item for every thread: each thread will run Queue.Queue.task_done()) that could stop the software if a thread doesn't terminate. So if a thread, among other 50, doesn't terminate then it is all freezed.

我希望每个线程都在5秒内停止.因此,我将以5秒的超时时间启动每个线程.正确吗?

I want that every thread stops in 5 seconds, for example. So i will start each thread with timeout of 5 seconds. Is it correct?

代码

import threading
import time

def tt(name, num):
    while True:
        num += 0.5
        print 'thread ' + str(name) + ' at time ' + str(num)
        time.sleep(0.5)


for i in range(3):
    t=threading.Thread(target=tt, args=(i, 0))
    t.setDaemon(True)
    t.start()
    t.join(timeout=1)

print 'end'

结果

它无法正常工作..每个线程应在1秒钟后停止.线程0在3秒后停止,线程1在2秒后停止.

It is not properly working.. every thread should stop after 1 second. Thread 0 stops after 3 secs, thread 1 after 2 secs.

thread 0 at time 0.5
thread 0 at time 1.0
thread 1 at time 0.5
thread 0 at time 1.5
thread 0 at time 2.0
thread 1 at time 1.0
thread 2 at time 0.5
thread 0 at time 2.5
thread 1 at time 1.5
thread 2 at time 1.0thread 1 at time 2.0

thread 0 at time 3.0
end

推荐答案

您误解了timeout的作用.它只是告诉join等待线程停止多长时间.如果超时到期后线程仍在运行,则join调用将结束,但线程将继续运行.

You're misunderstanding what timeout does. It just tells join how long to wait for the thread to stop. If the thread is still running after the timeout expires, the join call ends, but the thread keeps running.

从文档中

如果存在timeout参数而不是None, 它应该是一个浮点数,以秒为单位(或几分之一秒)指定操作的超时时间.由于join()始终返回None,因此必须在join()之后调用isAlive()来确定是否发生超时–如果线程仍然存在,则join()调用会超时.

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). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

这篇关于了解thread.join(timeout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆