gpt4 book ai didi

python - 在 Python 中设置阻塞函数超时

转载 作者:行者123 更新时间:2023-12-03 13:04:36 26 4
gpt4 key购买 nike

我有一个阻塞功能,有时它会无限期挂起,它不受 cpu 限制,它正在访问外部的东西,它也是对非托管代码的调用。我希望它可以在 Windows 或 Unix 上工作

超时运行此方法的最佳做法是什么?我认为这将涉及运行一个新线程并有一个等待事件。就代码行和 cpu 而言,我追求的是最轻量级的。

谢谢

最佳答案

您将使用 wait(timeout=None)使用池和异步调用时等待结果超时的方法:

>>> import multiprocessing
>>> p = multiprocessing.Pool()
>>> a = p.apply_async(None) # Replace None with the function to execute.
>>> help(a.__class__)
Help on class ApplyResult in module multiprocessing.pool:

class ApplyResult(builtins.object)
| Methods defined here:
|
| __init__(self, cache, callback, error_callback)
|
| get(self, timeout=None)
|
| ready(self)
|
| successful(self)
|
| wait(self, timeout=None)
[...]

concurrent.futures 也有 wait get 的方法或超时.

关于python - 在 Python 中设置阻塞函数超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com