Reputation: 31511
Consider a hypothetical threaded Python application that runs each thread in an infinite loop:
import signal
import sys
import threading
import time
class CallSomebody (threading.Thread):
def __init__(self, target, *args):
self._target = target
self._args = args
threading.Thread.__init__(self)
def run (self):
self._target(*self._args)
def call (who):
while True:
print "Who you gonna call? %s" % (str(who))
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
a=CallSomebody(call, 'Ghostbusters!')
a.daemon=True
b=CallSomebody(call, 'The Exorcist!')
b.daemon=True
a.start()
b.start()
a.join()
b.join()
When running the application, sending SIGINT by pressing CtrlC does not stop the application. I tried removing the daemon
statements but that did not help. What fundamental idea am I missing?
Thanks.
Upvotes: 2
Views: 153
Reputation: 48028
When you join
a thread the active thread blocks until the joined thread returns. Yours never do. You won't want to join them in this way.
Generally, background threads that are daemon threads and that perform infinite loops should be marked daemon, never joined, and then allowed to expire when your main thread does so. If you happened to be using wx
for example, you'd make your call to AppInstance.MainLoop()
after starting the daemonic threads, then when your Frame or whatever other top level instances you had were closed, the program execution would be concluded, and the daemons would be addressed appropriately.
Upvotes: 4