如何设置线程超时? [英] How to set timeout to threads?
问题描述
我正在使用threading.Thread
对我的代码进行多线程处理.
如果至少有一个线程未在X秒内完成工作,我想捕获Timeout exception
.
我在这里找到了一些答案,描述了如何解决该问题,但是大多数答案都与UNIX兼容,而我使用的是Windows平台.
I'm using threading.Thread
to multi-thread my code.
I want to catch Timeout exception
if at least 1 of the Threads did not finish their work in X seconds.
I found some answers here, describing how to deal with that, but most of them were UNIX compatible, whereas I'm using Windows platform.
例如代码:
from threading import Thread
from time import sleep
def never_stop():
while 1 > 0:
print 'a'
sleep(5)
print 'b'
return
t1 = Thread(target=never_stop)
t1.start()
t2 = Thread(target=never_stop)
t2.start()
t3 = Thread(target=never_stop)
t3.start()
t1.join(2)
t2.join(2)
t3.join(2)
我尝试在join
方法中设置超时,但是它没有用..
I tried to set timeout in the join
method but it was useless..
有什么想法吗?
推荐答案
来自文档:
当存在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.
这篇关于如何设置线程超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!