如何限制函数调用的执行时间? [英] How to limit execution time of a function call?

查看:104
本文介绍了如何限制函数调用的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个与socket相关的函数调用,该函数来自另一个模块,因此不受我的控制,问题是它偶尔会阻塞几个小时,这是完全不可接受的,我如何限制函数执行时间从我的代码?我想解决方案必须使用另一个线程.

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.

推荐答案

我不确定这可能是跨平台的,但使用信号和警报可能是看待这个问题的好方法.只需稍加努力,您就可以使其完全通用,并可在任何情况下使用.

I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.

http://docs.python.org/library/signal.html

所以你的代码看起来像这样.

So your code is going to look something like this.

import signal

def signal_handler(signum, frame):
    raise Exception("Timed out!")

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10)   # Ten seconds
try:
    long_function_call()
except Exception, msg:
    print "Timed out!"

这篇关于如何限制函数调用的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆