title: In python, is there a way to make threads that die when there is no longer a reference to them?
body: <p>Sometimes I want a class that is continuously updated by a worker thread that it spawns when it is created. Basically like this:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I want a safe way to design this so that I'm sure the thread dies when the <code>MyWidget</code> is no longer needed. The problem with the above code is that the <code>MyWidget</code> will never die because it is being kept alive by the <code>MyThread</code>. I can fix that by giving the <code>MyThread</code> a <code>weakref.ref</code> to the <code>MyWidget</code> and breaking the loop when the reference dies but I have made the mistake of not doing this in the past.</p>
  
  <p>What I'd really like is threads that get garbage collected along with everything else. ie. A thread that is killed when it's reference graph and the main thread's reference graph are disjoint. Would it be possible to write such a beast? Do they already exist?</p>