【发布时间】:2015-04-22 09:22:09
【问题描述】:
类似的问题我已经问过很多次了,但还是找不到合适的解决方案。
我有一个外部函数,在某些情况下可以运行很长时间。我想在 30 秒后打断它。
我该怎么做?
- 线程很好,但我无法阻止它们(我无权访问外部函数的代码)
- 多处理也不是一个选项,因为我在 mod_wsgi 下运行站点。
有没有可靠的方法来停止线程? 也许使用 os.system 或 os.kill。如果是,那么如何?
外部函数只执行一些计算,没有网络连接或文件打开。所以,我只需要停止进程并清理即可。
我的代码(实际上取自某个来源):
def time_limit(timeout):
def internal(function):
def internal2(*args, **kw):
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
self.error = None
def run(self):
try:
self.result = function(*args, **kw) # this is external
except Exception as e:
self.error = e
def _stop(self):
if self.isAlive():
threading.Thread._Thread__stop(self)
c = MyThread()
c.start()
c.join(timeout)
counter = 0
if c.isAlive():
c._stop()
raise TimeoutException
if c.error:
raise c.error
return c.result
return internal2
return internal
【问题讨论】:
标签: python linux multithreading