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.