Home
Posts
Categories
Tags
About
python 关闭子线程
发布于: 2022-11-16   更新于: 2022-11-16   收录于: python
本文字数: 112   阅读时间: 1 分钟  

关闭子线程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from threading import Thread
from ctypes import c_long, pythonapi, py_object


class thread(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
        super().__init__(group, target, name, args, kwargs, daemon=daemon)

    def stop(self):
        tid = c_long(self.ident)
        res = pythonapi.PyThreadState_SetAsyncExc(tid, py_object(SystemExit))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")

        self._started.clear()

    def run(self):
        try:
            if self._target:
                self._target(*self._args, **self._kwargs)
        finally:
            self._started.clear()


一般不建议使用,可能会导致内存泄漏