我发现了一个创建超时函数here的代码,它似乎不起作用。完整的测试代码如下:
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result
def foo():
while True:
pass
timeout(foo,timeout_duration=3)预期行为:代码在3秒内结束。问题出在哪里?
发布于 2012-12-11 21:13:46
您需要将it转换为daemon thread
it = ...
it.daemon = True
it.start()否则,它将被创建为用户线程,并且在所有用户线程完成之前,该进程不会停止。
请注意,在您的实现中,即使在等待线程超时之后,线程仍将继续运行并消耗资源。CPython的Global Interpreter Lock可能会进一步加剧这个问题。
https://stackoverflow.com/questions/13821156
复制相似问题