python中优雅的杀死线程

  上一篇博客中,杀死线程采用的方法是在线程中抛出异常   python中杀死线程 - 永恒de记忆 - 博客园, 这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。

      有一种更优雅的杀死线程的方法就是使用退出标记,这里使用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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值