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")

 

posted @ 2019-12-05 20:26  永恒de记忆  阅读(7446)  评论(1编辑  收藏  举报