Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Signals in Python Threads

I have a threaded application written in Python, and whenever an interrupt is received via Ctrl+C or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with Ctrl+Z then attempt to kill it.

What is the proper way of handling signals and keyboard interrupts inside of a threaded application?

like image 430
Eric Pruitt Avatar asked Jan 06 '11 15:01

Eric Pruitt


4 Answers

If you set newthread.daemon = True before starting each thread, the threads will automatically be killed when the main thread exits. That's not precisely what you were asking, but from what you've described, it sounds like it could be worth knowing.

like image 93
Thomas K Avatar answered Oct 05 '22 09:10

Thomas K


The way I worked around this issue was to make a module that could kept a list of threads. The module also had a method that killed every thread in that list. I registered this method to be called when the SIGINT signal was received. Lastly, I created a wrapper class for Thread that would automatically add the created instance to the list of threads.

like image 25
unholysampler Avatar answered Oct 05 '22 08:10

unholysampler


CPython Threading: Interrupting covers what happens to signals in Python threads, and various solutions to your problem. It is a good read.

like image 20
brildum Avatar answered Oct 05 '22 10:10

brildum


Use the signal module and continue reading here Signal handlers and logging in Python about possible pitfalls.

In order to catch Ctrl+C actions from the user you have to profice a signal handler for SIGINT.

Within the signal handler notify (message queues or RLock synchronized attribute access) your threads to shutdown, or what ever you intent to do.

like image 34
Raphael Bossek Avatar answered Oct 05 '22 08:10

Raphael Bossek