How to terminate a thread when main program ends? How to terminate a thread when main program ends? multithreading multithreading

How to terminate a thread when main program ends?


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


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


Try with enabling the sub-thread as daemon-thread.

For Instance:

Recommended:

from threading import Threadt = Thread(target=<your-method>)t.daemon = True  # This thread dies when main thread (only non-daemon thread) exits.t.start()

Inline:

t = Thread(target=<your-method>, daemon=True).start()

Old API:

t.setDaemon(True)t.start()

When your main thread terminates ("i.e. when I press Ctrl+C"), other threads will also be killed by the instructions above.