使用OS杀死python线程 [英] Kill python thread using os

查看:371
本文介绍了使用OS杀死python线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次问过类似的问题,但仍然找不到合适的解决方案.

I've already asked similar question many times, but still can't find appropriate solution.

我具有外部功能,在某些情况下可以运行很长时间.我想在30秒后中断它.

I have and external function, that could run in some cases very long. I want to interrupt it after, say, 30 seconds.

我该怎么做?

  1. 线程是好的,但我无法阻止它们(我无法访问外部函数的代码)
  2. 也不能选择多处理,因为我在mod_wsgi下运行站点.

有没有可靠的方法来停止线程? 也许使用os.system或os.kill.如果是,那怎么办?

Are there any reliable ways to stop the thread? Maybe using os.system or os.kill. If yes, then how?

外部功能仅执行一些计算,没有网络连接或文件打开.因此,我只需要停止进程并进行清理即可.

External function only performs some caclulations, no network connections or file openings. So, I just need to stop process and clean up.

我的代码(实际上是从某些来源获取的):

My code (actually was taken from some source):

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

推荐答案

您不能杀死线程,但是可以杀死进程.如果可以使用进程代替线程,则可以使用多线程模块.可以从父应用程序终止

You can't kill thread, but you can kill a process. If you can use processes instead threads, you can use multithreading module. Process can be terminated from parent application.

如果您更详细地描述您的任务,也许我可以提供更多帮助.

If you describe your task in more detail, maybe I can help more.

这篇关于使用OS杀死python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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