Python 实现关闭线程

817 阅读1分钟

粗暴地直接杀死线程

    利用python内置API,通过ctypes模块调用,在线程中丢出异常,使线程退出。

import time
import ctypes
import inspect
import threading


def _async_raise(tid, exctype):
    """
    raise the exception, performs cleanup if needed
    """
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # if it returns a number greater than one, should call it again with exc=NULL to revert the effect
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

利用标识符使线程自杀

    自定义一个拥有停止方法的线程。

import threading
import subprocess


class StopAbleThread(threading.Thread):
    """
    Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition.
    """
    def __init__(self, *args, **kwargs):
        super(StopAbleThread, self).__init__(*args, **kwargs)
        self._stop_event = threading.Event()

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

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

    def run(self):
        while True:
            print("running")
            if self.stopped():
                break