In python, is there a way to make threads that die when there are no more references to them?

Sometimes I need a class that is constantly updated by the workflow that it spawns when it is created. Mostly like this:

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)

I want to create a safe way for this so that I am sure that the thread dies when it is MyWidgetno longer needed. The problem with the above code is that it MyWidgetwill never die, because it is supported in mode MyThread. I can fix this by pointing MyThreada weakref.refto MyWidgetand breaking the loop when this link dies, but I made a mistake without doing this in the past.

, . . , , , . ? ?

+5
1

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.

+1

All Articles