首页 > 解决方案 > Python thread.join(超时)没有超时

问题描述

我正在使用线程 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 :(

为什么会这样,我该如何解决这种行为?我应该尝试使用多处理吗?

标签: pythonmultithreadingpython-multiprocessingpython-multithreading

解决方案


我怀疑在这种情况下,您遇到了一个问题,即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"这按预期打印。


推荐阅读