If I have a thread in an infinite loop, is there a way to terminate it when the main program ends (for example, when I press Ctrl+C)?
6 Answers
If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.
http://docs.python.org/library/threading.html#threading.Thread.daemon

- 22,757
- 7
- 55
- 61
-
5Thanks for the simple and precise answer, the default threading.Thread daemon status `isDaemon()` is False, set it True by `setDaemon(True)`. – Tong Jun 24 '15 at 02:42
-
3This answers the question and just works. The op did not ask how to exit threads cleanly in general. – Johannes Overmann Jul 26 '15 at 20:27
-
4`isDaemon()` and `setDaemon()` are old getters/setters (as per the linked doc above), just use `daemon=True` in `threading.Thread()` – fabio.sang Jul 08 '18 at 06:30
-
2Note that using daemon threads can cause other issues and is probably not what you want here: https://stackoverflow.com/questions/20596918/python-exception-in-thread-thread-1-most-likely-raised-during-interpreter-shutd/20598791#20598791 – Doopy Apr 28 '20 at 14:34
-
To avoid using daemon threads and cleanly kill threads, see https://stackoverflow.com/questions/58910372/script-stuck-on-exit-when-using-atexit-to-terminate-threads – user Nov 08 '20 at 00:37
Check this question. The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?
To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:
try:
start_thread()
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread()
sys.exit()
This way you can control what to do whenever the program is abruptly terminated.
You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html

- 1
- 1

- 51,659
- 8
- 55
- 58
-
Thanks a lot for your reply. I might have not stated the question correctly. In the example given in that question it was still necessary to execute the thread's stop() function. When I terminate a program abnormally by ctrl+C, that can't happen. So, my question is a bit like, "how do I call the mythread.stop() funcion if the main thread flow is interrupted" – facha Apr 01 '10 at 23:08
-
1Is `cleanup_stop_thread()` a global function that I can use? or should I need to implement it? – alper May 21 '20 at 11:58
-
@alper, I think maybe it was just an example that is possible to implement something. You should implement that – Leonardo Rick Sep 12 '20 at 18:43
Try to enable the sub-thread as daemon-thread.
Recommended:
from threading import Thread
t = Thread(target=desired_method)
t.daemon = True # Dies when main thread (only non-daemon thread) exits.
t.start()
Inline:
t = Thread(target=desired_method, daemon=True).start()
Old API:
t.setDaemon(True)
t.start()
When your main thread terminates (e.g. Ctrl+C keystrokes), other threads will also be killed by the instructions above.

- 27,880
- 26
- 135
- 150
-
2Note that using daemon threads can cause other issues and are probably not what you want here: https://stackoverflow.com/questions/20596918/python-exception-in-thread-thread-1-most-likely-raised-during-interpreter-shutd/20598791#20598791 – Doopy Apr 28 '20 at 14:49
Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt
. Such termination functions may (though inevitably in the main thread!) call any stop
function you require; together with the possibility of setting a thread as daemon
, that gives you the tools to properly design the system functionality you need.

- 854,459
- 170
- 1,222
- 1,395
-
Note that this approach worked without requiring daemonized threads in Python versions prior to 2.6.5, see answer to http://stackoverflow.com/questions/3713360/python-2-6-x-theading-signals-atexit-fail-on-some-versions. This is unfortunate IMHO, since daemon threads during shutdown are a bit of a mess before python 3.4 (http://bugs.python.org/issue19466). If you stop _and_ join your daemon threads in your atexit handlers, all should be fine, at the (probably insignificant) cost of serializing your thread teardown. – NeilenMarais Jan 15 '15 at 14:04
-
Be aware that weird things can happen because of post-poned `atexit.register()` calls in Python modules, causing your termination procedure to be executed after the `multiprocessing`'s one. I run in this problem dealing with `Queue` and `daemon` threads: [“EOF error” at program exit using multiprocessing Queue and Thread](https://stackoverflow.com/questions/49209385/eof-error-at-program-exit-using-multiprocessing-queue-and-thread/49244528#49244528). – Delgan Mar 12 '18 at 21:33
-
1Apparently in modern versions of Python, such as 3.7.4+, the `atexit` handlers aren't called when non-daemon threads are alive and the main thread exits. See [Script stuck on exit when using atexit to terminate threads](https://stackoverflow.com/questions/58910372/script-stuck-on-exit-when-using-atexit-to-terminate-threads). – martineau Nov 20 '19 at 00:57
If you spawn a Thread like so - myThread = Thread(target = function)
- and then do myThread.start(); myThread.join()
. When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join()
call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True
so all the threads exit when the main thread(non-daemon) exits.

- 878
- 9
- 16
-
-
6@Brannon `.daemon=True` is in not a solid solution. Check this thread for an explanation: https://stackoverflow.com/a/20598791/5562492 – Odyssee Oct 19 '17 at 20:47
Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.
E.g. for Python 3:
while threading.main_thread().isAlive():
do.you.subthread.thing()
gracefully.close.the.thread()
See Check if the Main Thread is still alive from another thread.

- 3,782
- 2
- 15
- 12