在python中,有没有办法让线程在不再引用它们时死掉?

Shu*_*hum 5 python multithreading

有时我想要一个由工作线程不断更新的类,它在创建时会产生.基本上是这样的:

class MyWidget:
    def __init__(self):
        self.blah = None
        self.thread = MyThread(self)
        self.thread.start()

    def update(self, blah):
        self.blah = blah

class MyThread(threading.Thread):
    def __init__(self, widget):
        self.widget = widget

    def run(self):
        while True:
            time.sleep(1)
            blah = poll()
            self.widget.update(blah)
Run Code Online (Sandbox Code Playgroud)

我想要一个安全的方法来设计这个,以便我确定线程在MyWidget不再需要时死掉.上面代码的问题MyWidget在于它永远不会死,因为它会被它保持活着MyThread.我可以给修复MyThreadweakref.refMyWidget,打破循环的时候参考模,但我已经在过去没有这样的错误.

我真正喜欢的是将垃圾与其他一切一起收集的线程.即.当它的引用图和主线程的引用图是不相交时被杀死的线程.是否有可能写出这样的野兽?他们已经存在吗?

Mat*_*vor 2

如果修改MyThread为提供一个stop方法:

class MyThread(threading.Thread):
    def __init__(self, widget):
        self.widget = widget
        self.is_running = False
        super(MyThread, self).__init__()

    def run(self):
        self.is_running = True
        while self.is_running:
            time.sleep(1)
            blah = poll()
            self.widget.update(blah)

    def stop(self):
        self.is_running = False
Run Code Online (Sandbox Code Playgroud)

如果MyWidget不再需要您的实例,您可以调用widget.thread.stop(),这将杀死线程并允许所有内容被 GC 处理。