Python threads, thread is not informed to stop
Question: I would like to stop a Python thread when the main program stops. It is for a
class that connects to a server. The connection is maintained by the
background thread, the foreground thread answers to callbacks. The following
is a minimal example.

    
    
    #!/usr/bin/python
    import time, threading
    class test():
        running = False
        def __init__(self):
            print "init"
            self.running = True
            self.thread = threading.Thread(target = self.startThread)
            self.thread.start()
    
        def __del__(self):
            running = False
            print "del"
    
        def startThread(self):
            print "thread start"
            while self.running:
                time.sleep(1)
                print "thread running"
    
    a = test()
    

When the program ends, I would naively expect __del__() to be called so that
the background thread can be informed to stop, but i is not called untill
after the background thread stops. Explicitly calling some function is not an
option since the class is used by other people, whom I do not want to force to
use some extra lines of code.


Answer: `__del__` is not called as long as there are references to `self`, and you
have one such reference in the background thread itself: in the `self`
argument of `def startThread(self):`.

You need to move the function that runs the background thread outside of the
class. And rather than a `__del__` I would recommend for example using a
weakref, as follows. This code should work without the `__del__()` method and
without using a `self.running` attribute.

    
    
    self.thread = threading.Thread(target=run_me, args=(weakref.ref(self),))
    ...
    def run_me(weak_self):
        "Global function"
        while True:
            self = weak_self()
            if self is None: break    # no more reference to self
            ...
            del self        # forget this reference for now
            time.sleep(1)
    

