理解 thread.join(timeout)
所以线程的 timeout 参数应该在 timeout 秒后停止这个线程(如果它还没有结束的话)。
在我的软件中,我想替换掉 Queue.Queue.join() 这个功能(它为每个线程都包含一个项目:每个线程会运行 Queue.Queue.task_done()),因为如果一个线程没有结束,可能会导致软件停止工作。所以如果有一个线程在50个线程中没有结束,整个程序就会卡住。
我希望每个线程在5秒内停止,比如说。所以我打算给每个线程设置5秒的超时,这样做对吗?
代码
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秒后停止。
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
1 个回答
38
你可能误解了 timeout
的作用。它只是告诉 join
等待线程停止的时间。如果在超时时间到达后,线程还在运行,join
就会结束,但线程仍然会继续运行。
根据文档的说明:
当提供了超时参数并且它不是 None 时,它应该是一个浮点数,表示操作的超时时间,单位是秒(或者小数部分)。由于
join()
总是返回 None,所以你必须在join()
之后调用isAlive()
来判断是否发生了超时——如果线程仍然在运行,说明join()
调用超时了。