首页 > 编程语言 > 详细

python中优雅的杀死线程

时间:2019-12-05 21:03:48      阅读:113      评论:0      收藏:0      [点我收藏+]

      上一篇博客中,杀死线程采用的方法是在线程中抛出异常   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")

 

python中优雅的杀死线程

原文:https://www.cnblogs.com/lucky-heng/p/11991695.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!