108

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 6

136

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the simple and precise answer, the default threading.Thread daemon status isDaemon() is False, set it True by setDaemon(True).
This answers the question and just works. The op did not ask how to exit threads cleanly in general.
isDaemon() and setDaemon() are old getters/setters (as per the linked doc above), just use daemon=True in threading.Thread()
Note that using daemon threads can cause other issues and is probably not what you want here: stackoverflow.com/questions/20596918/…
To avoid using daemon threads and cleanly kill threads, see stackoverflow.com/questions/58910372/…
48

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

3 Comments

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"
Is cleanup_stop_thread() a global function that I can use? or should I need to implement it?
@alper, I think maybe it was just an example that is possible to implement something. You should implement that
37

Try to enable the sub-thread as daemon-thread.

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.

1 Comment

Note that using daemon threads can cause other issues and are probably not what you want here: stackoverflow.com/questions/20596918/…
12

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.

3 Comments

Note that this approach worked without requiring daemonized threads in Python versions prior to 2.6.5, see answer to stackoverflow.com/questions/3713360/…. This is unfortunate IMHO, since daemon threads during shutdown are a bit of a mess before python 3.4 (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.
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.
Apparently 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.
9

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.

2 Comments

myThread.daemon = True is a wonderful solution to this problem.
@Brannon .daemon=True is in not a solid solution. Check this thread for an explanation: stackoverflow.com/a/20598791/5562492
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.