Py学习  »  Python

强制退出运行python中的线程[duplicate]

Viet Phan • 6 年前 • 4773 次点击  

是否可以在不设置/检查任何标志/信号量/等的情况下终止正在运行的线程?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41119
 
4773 次点击  
文章 [ 24 ]  |  最新文章 6 年前
schettino72
Reply   •   1 楼
schettino72    15 年前

如果试图终止整个程序,可以将线程设置为“守护进程”。看见 Thread.daemon

cfi
Reply   •   2 楼
cfi    13 年前

multiprocessing.Process 可以 p.terminate()

如果我想杀死一个线程,但不想使用flags/locks/signals/semaphores/events/whatever,我会将线程提升为完全成熟的进程。对于只使用几个线程的代码,开销并没有那么大。

例如,这可以方便地终止执行阻塞I/O的助手“线程”

转换很简单:在相关代码中全部替换 threading.Thread 具有 多处理过程 以及所有 queue.Queue 具有 multiprocessing.Queue 并添加所需的调用 P.终止() 你的父进程想要杀死它的子进程 p

Python doc

Martin v. Löwis
Reply   •   3 楼
Martin v. Löwis    16 年前

没有官方的api可以做到这一点,不。

您需要使用平台api来终止线程,例如pthread_kill或terminatethread。您可以通过pythonwin或cTypes访问此类API。

请注意,这本质上是不安全的。它可能会导致无法收集的垃圾(来自成为垃圾的堆栈帧的局部变量),如果被杀死的线程在被杀死的时候具有gil,则可能导致死锁。

Richard Möhn Philippe F
Reply   •   4 楼
Richard Möhn Philippe F    7 年前

在python和任何语言中,突然终止线程通常都是一种糟糕的模式。请考虑以下情况:

  • 线程正在保存一个必须正确关闭的关键资源
  • 该线程已经创建了几个其他线程,这些线程也必须被终止。

如果您负担得起(如果您管理自己的线程),处理这个问题的好方法是有一个exit_request标志,每个线程都会定期检查这个标志,看是否是时候让它退出了。

例如:

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

在这段代码中,您应该在希望线程退出时对其调用stop(),并使用join()等待线程正确退出。线程应定期检查停止标志。

但也有一些情况下,你真的需要杀死一个线程。一个例子是,当您包装一个外部库时,该库正忙着长时间的调用,并且您想中断它。

以下代码允许(有一些限制)在python线程中引发异常:

def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
                                                     ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # "if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"
        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising exception in the thread from
       another thread.
    '''
    def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL : this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        # TODO: in python 2.6, there's a simpler way to do : self.ident

        raise AssertionError("could not determine the thread's id")

    def raiseExc(self, exctype):
        """Raises the given exception type in the context of this thread.

        If the thread is busy in a system call (time.sleep(),
        socket.accept(), ...), the exception is simply ignored.

        If you are sure that your exception should terminate the thread,
        one way to ensure that it works is:

            t = ThreadWithExc( ... )
            ...
            t.raiseExc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raiseExc( SomeException )

        If the exception is to be caught by the thread, you need a way to
        check that your thread has caught it.

        CAREFUL : this function is executed in the context of the
        caller thread, to raise an excpetion in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

基于 Killable Threads 托默·菲利巴。关于 PyThreadState_SetAsyncExc 似乎来自 old version of Python )

如文档中所述,这不是一个神奇的项目符号,因为如果线程在python解释器之外很忙,它将不会捕捉到中断。

这段代码的一个好的使用模式是让线程捕获一个特定的异常并执行清理。这样,你可以中断一个任务,仍然有适当的清理。