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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看