python - 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 :(
为什么会这样,我该如何解决这种行为?我应该尝试使用多处理吗?
解决方案
我怀疑在这种情况下,您遇到了一个问题,即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"
这按预期打印。
推荐阅读
- c# - 无法将 System.Windows.Forms.Form 隐式转换为“字符串”
- aws-lambda - AWS cron expression OK, lambda not triggered
- scala - Spark SQL - Check for a value in multiple columns
- codenameone - Updating TableModel of spanned cell setHorizontalSpan causes IllegalArgumentException
- mysql - SQL 对某行进行计数和求和
- r - 从向量列表中减去单个向量元素
- windows - 并行调用 VhfReadReportSubmit 导致 Stack Overflow BSOD
- c++ - :-1: 错误:依赖 'D:\Storage\C++_Libraries\Qt\5.15.0\mingw81_32\lib\Qt5Widgetsd.lib' 不存在
- python - 尽管安装并添加了路径变量,但无法在 Windows 上运行 uvicorn 命令
- html - display:grid 是否可以在父级上使用 100% 的高度?