Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a thread when main program ends?

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)?

like image 396
facha Avatar asked Apr 01 '10 22:04

facha


People also ask

What happens to any thread after the main program ends?

All the threads in your process will be terminated when you return from main() .

How do you terminate a thread?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

What happens to thread when process exits?

Exiting the main thread will not result in the process exiting if there are any other threads still active. According to the old-fashioned model of how processes exit, a process was in control of all its threads and could mediate the shutdown of those threads, thereby controlling the shutdown of the process.

How do you force stop a thread in Python?

Using a hidden function _stop() : In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.


2 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

like image 127
ʇsәɹoɈ Avatar answered Sep 21 '22 04:09

ʇsәɹoɈ


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

like image 22
rogeriopvl Avatar answered Sep 18 '22 04:09

rogeriopvl