python 如何 kill 掉运行中的 thread

通过threading启用多线程,如下

            for i in range(3):
                th = threading.Thread(target=self.kafka_producer)
                kafka_producer_thread_list.append(th)
            print(kafka_producer_thread_list)

[<Thread(Thread-34, started 21640)>, <Thread(Thread-35, started 18996)>, <Thread(Thread-36, started 24568)>]
用cmd来kill,发现失败
taskkill /pid 21640 /f
错误: 没有找到进程 "21640"。
请问原因是何?或者有没有其他办法停止Thread

没有现成的方法, 需要自己实现


from threading import Thread
import time
import inspect
import ctypes


def _async_raise(tid, exctype):
    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, you're in trouble,
        # and you 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):
    thread._is_stopped = True  # 修改线程状态
    _async_raise(thread.ident, SystemExit)


def task():
    for i in range(1, 100):
        print(i)
        time.sleep(1)


if __name__ == '__main__':
    th = Thread(target=task)
    th.start()  # 开始线程
    print(th.is_alive())  # 查看线程运行状态
    time.sleep(2)
    stop_thread(th)  # 终止线程
    print(th.is_alive())  # 查看线程运行状态

运行结果:

img

cmd是用来kill进程的
你这是线程啊
具体自行百度:python杀死线程
因为没有提供杀死线程的函数,需要你自己实现,比较复杂