使用 __del__ 停止 python 线程 [英] stopping a python thread using __del__

查看:107
本文介绍了使用 __del__ 停止 python 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个线程程序,它工作正常,只是线程运行后不​​会调用 __del__:

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

例如如果我这样做

tc = aa()
del tc 

它工作正常(我得到删除消息暂停等).但是,如果我这样做:

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

tc = aa()
tc.start()
del tc

然后 __del__ 不会运行(注意,当我执行 tc.start(); tc.stop(); del tc 时它确实执行了 __del__.

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

我在 ipython 中运行这个

I'm running this in ipython

推荐答案

__del__() 方法在实例被垃圾回收时执行,而不是在调用 del 时执行在碰巧指向实例的名称上.后者只会删除名称(这在某些情况下可能会导致名称指向的实例被 gc'ed).

The __del__() method is executed when an instance is garbage collected, not when you call del on a name that happens to point to the instance. The latter will only delete the name (which might in some cases result in the instance pointed to by the name being gc'ed).

threading.Thread 实例永远不会在线程仍在运行时被垃圾回收,因为在这种情况下该实例仍在使用中.并且放弃一个碰巧指向实例的名称肯定不会停止线程.

A threading.Thread instance will never be garbage collected while the thread is still running, since the instance is still in use in this case. And ditching a name that happens to point to the instance certainly won't stop the thread.

这篇关于使用 __del__ 停止 python 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆