多处理函数上的超时装饰器
我的这个装饰器直接取自我在网上找到的一个示例:
class TimedOutExc(Exception):
pass
def timeout(timeout):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
result = f(*args, **kwargs)
except TimedOutExc:
return None
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
new_f.func_name = f.func_name
return new_f
return decorate
如果 f 函数超时,它会抛出异常。
嗯,它有效,但是当我在多处理函数上使用这个装饰器并由于超时而停止时,它不会终止计算中涉及的进程。我怎样才能做到这一点?
我不想启动异常并停止程序。基本上我想要的是当 f 超时时,让它返回 None 然后终止所涉及的进程。
I have this decorator taken directly from an example I found on the net:
class TimedOutExc(Exception):
pass
def timeout(timeout):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
result = f(*args, **kwargs)
except TimedOutExc:
return None
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
new_f.func_name = f.func_name
return new_f
return decorate
It throws an exception if the f function times out.
Well, it works but when I use this decorator on a multiprocessing function and stops due to a time out, it doesn't terminate the processes involved in the computation. How can I do that?
I don't want to launch an exception and stop the program. Basically what I want is when f times out, have it return None and then terminate the processes involved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我同意亚伦回答的要点,但我想详细说明一下。
由
multiprocessing
启动的进程必须在要修饰的函数中停止;我认为这不能从装饰器本身一般且简单地完成(装饰函数是唯一知道它启动了什么计算的实体)。您还可以捕获自定义的
TimedOutExc
异常,而不是让装饰函数捕获SIGALARM
,这可能更灵活。那么你的例子将变成:While I agree with the main point of Aaron's answer, I would like to elaborate a bit.
The processes launched by
multiprocessing
must be stopped in the function to be decorated; I don't think that this can be done generally and simply from the decorator itself (the decorated function is the only entity that knows what calculations it launched).Instead of having the decorated function catch
SIGALARM
, you can also catch your customTimedOutExc
exception–this might be more flexible. Your example would then become:我怀疑这可以通过装饰器来完成:装饰器是函数的包装器;该函数是一个黑匣子。装饰器和它所包装的函数之间没有通信。
您需要做的是重写函数的代码以使用
SIGALRM
处理程序来终止它已启动的任何进程。I doubt that can be done with a decorator: A decorator is a wrapper for a function; the function is a black box. There is no communication between the decorator and the function it wraps.
What you need to do is rewrite your function's code to use the
SIGALRM
handler to terminate any processes it has started.