supper_boss 2021-09-29 15:39 采纳率: 72.7%
浏览 18
已结题

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

  • 写回答

2条回答 默认 最新

  • 给你骨质唱疏松 2021-09-29 15:46
    关注

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

    
    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月7日
  • 已采纳回答 9月29日
  • 创建了问题 9月29日

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了