supper_boss 2021-09-29 11:46 采纳率: 72.7%
浏览 175
已结题

python问题,threading如何stop

self.th = threading.Thread(target=self.fun)
用 th.stop() 会报错 'Thread' object has no attribute 'stop',请教threading如何在运行过程中停止

  • 写回答

3条回答 默认 最新

  • 给你骨质唱疏松 2021-09-29 15:48
    关注
    
    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

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

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用