zoukankan      html  css  js  c++  java
  • python中优雅的杀死线程

          上一篇博客中,杀死线程采用的方法是在线程中抛出异常   https://www.cnblogs.com/lucky-heng/p/11986091.html, 这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。

          有一种更优雅的杀死线程的方法就是使用退出标记,这里使用threading.Event()创建一个事件管理标记flag,这种方法是更安全的。

    # encoding:utf-8
    import time
    import threading
    
    
    class StoppableThread(threading.Thread):
        """Thread class with a stop() method. The thread itself has to check
        regularly for the stopped() condition."""
    
        def __init__(self,  *args, **kwargs):
            super(StoppableThread, self).__init__(*args, **kwargs)
            self._stop_event = threading.Event()
    
        def stop(self):
            self._stop_event.set()
    
        def stopped(self):
            return self._stop_event.is_set()
    
        def run(self):
            print("begin run the child thread")
            while True:
                print("sleep 1s")
                time.sleep(1)
                if self.stopped():
                    # 做一些必要的收尾工作
                    break
    
    
    if __name__ == "__main__":
        print("begin run main thread")
        t = StoppableThread()
        t.start()
        time.sleep(3)
        t.stop()
        print("main thread end")
  • 相关阅读:
    8.02_python_lx_day14
    8.02_python_lx_day13<2>
    8.02_python_lx_day13<1>
    7.30_python_lx_day20
    7.29_python_lx_da19
    7.29_python_lx_day12
    Docker镜像
    Docker学习Ⅱ
    Docker学习Ⅰ
    2-3树的插入和删除原理
  • 原文地址:https://www.cnblogs.com/lucky-heng/p/11991695.html
Copyright © 2011-2022 走看看