Python thread.join(timeout) 没有超时
Python thread.join(timeout) not timing out
我正在使用线程 python 模块。我想执行一个运行用户输入的表达式的函数。我想等待它完成执行或直到达到超时期限。以下代码应在 5 秒后超时,但它永远不会超时。
def longFunc():
# this expression could be entered by the user
return 45 ** 10 ** 1000
thread = threading.Thread(target=longFunc, args=(), daemon=True)
thread.start()
thread.join(5.0)
print("end") # never reaches this point :(
为什么会这样,我该如何解决这个问题?我应该尝试改用多处理吗?
我怀疑在这种情况下,您遇到了一个问题,即 join
无法执行,而全局解释器锁由非常长的 运行 计算持有,我相信这会作为单个原子操作发生。如果您将 longFunc
更改为在多条指令上发生的事情,例如繁忙的循环,例如
def longFunc():
while True:
pass
然后它按预期工作。单个昂贵的计算是否符合您的情况,或者该示例是否恰好遇到了非常糟糕的情况?
使用 multiprocessing
模块似乎可以解决此问题:
from multiprocessing import Process
def longFunc():
# this expression could be entered by the user
return 45 ** 10 ** 1000
if __name__ == "__main__":
thread = Process(target=longFunc, args=(), daemon=True)
thread.start()
thread.join(5.0)
print("end")
这会按预期打印 "end"
。
我正在使用线程 python 模块。我想执行一个运行用户输入的表达式的函数。我想等待它完成执行或直到达到超时期限。以下代码应在 5 秒后超时,但它永远不会超时。
def longFunc():
# this expression could be entered by the user
return 45 ** 10 ** 1000
thread = threading.Thread(target=longFunc, args=(), daemon=True)
thread.start()
thread.join(5.0)
print("end") # never reaches this point :(
为什么会这样,我该如何解决这个问题?我应该尝试改用多处理吗?
我怀疑在这种情况下,您遇到了一个问题,即 join
无法执行,而全局解释器锁由非常长的 运行 计算持有,我相信这会作为单个原子操作发生。如果您将 longFunc
更改为在多条指令上发生的事情,例如繁忙的循环,例如
def longFunc():
while True:
pass
然后它按预期工作。单个昂贵的计算是否符合您的情况,或者该示例是否恰好遇到了非常糟糕的情况?
使用 multiprocessing
模块似乎可以解决此问题:
from multiprocessing import Process
def longFunc():
# this expression could be entered by the user
return 45 ** 10 ** 1000
if __name__ == "__main__":
thread = Process(target=longFunc, args=(), daemon=True)
thread.start()
thread.join(5.0)
print("end")
这会按预期打印 "end"
。