tags:

views:

354

answers:

3

Hi, everyone

If have a thread in infinite loop, is there a way to terminate it when main program ends (for example, when I press ctrl+C)?

+3  A: 

Check this question. The correct answer has great explanation on how to terminate threads the right way: http://stackoverflow.com/questions/323972/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 "KeyboardInterrup" 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

rogeriopvl
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
I edited my question :)
rogeriopvl
+1  A: 

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

Forest
+2  A: 

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.

Alex Martelli