python删除线程,使用__del__停止python线程

本文探讨了Python中线程管理的问题,特别是当尝试使用`__del__`方法停止线程时遇到的挑战。在Python中,`__del__`在对象被垃圾收集时调用,而不是直接通过`del`语句删除引用时。如果线程正在运行,线程实例不会被垃圾收集,因此`__del__`不会执行。解决方案是使用线程的`Event`对象来控制线程的停止,而不是依赖于`__del__`方法。
摘要由CSDN通过智能技术生成

I have a threaded program in Python that works fine except that __del__ does not get called once the thread is running:

class tt(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

self.stop_event = threading.Event()

def __del__(self):

print "Deleting"

self.stop_event.set()

time.sleep(5)

def run(self):

self.stop_event.clear()

while not self.stop_event.isSet():

self.do_stuff()

threading.Thread.__init__(self)

def stop(self):

self.stop_event.set()

For example if I do

tc = aa()

del tc

It works fine (I get the deleting message pause etc). However if I do:

tc = aa()

tc.start()

del tc

Then the __del__ does not get run (Note it does execute __del__ when I do tc.start(); tc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值