在python中,当不再有对线程的引用时,有没有一种方法可以使线程死亡?

2024-04-29 15:02:42 发布

您现在位置:Python中文网/ 问答频道 /正文

有时我需要一个类,该类在创建时由它派生的工作线程不断更新。基本上是这样的:

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)

我想要一个安全的方法来设计它,这样我就可以确定当不再需要MyWidget时线程会死掉。上面代码的问题是MyWidget永远不会死,因为它被MyThread保持活着。我可以通过给MyThread一个weakref.refMyWidget并在引用终止时中断循环来解决这个问题,但我犯了一个错误,过去没有这样做。你知道吗

我真正想要的是那些和其他东西一起被垃圾收集的线程。当它的引用图和主线程的引用图不相交时被终止的线程。有可能写出这样的怪兽吗?它们已经存在了吗?你知道吗


Tags: selfnoneinitdefupdatewidget线程thread
1条回答
网友
1楼 · 发布于 2024-04-29 15:02:42

如果修改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

如果在不再需要MyWidget实例的时候,您可以调用widget.thread.stop(),这将终止线程并允许对所有内容进行GC'd

相关问题 更多 >