Terminating threaded programs

mk mrkafk at gmail.com
Fri Feb 5 10:25:42 EST 2010


Hello everyone,

I have a problem with a threaded program: it frequently hangs on sys.exit.

The problem is that my program uses threads which in turn use paramiko 
library, which itself is threaded.

I try to gracefully close the threads (below), but it doesn't always 
work, if paramiko calls happen to be at stage of negotiating ssh 
connection or smth similar.

The only workable solution I have is a program sending itself SIGKILL, 
which makes it terminated by OS (I think so).

Is there any way to brutally close the threads? I know that normally 
that should not be done, but shutdown when you don't care about writing 
out to disk is the only situation where it doesn't apply.

def ctrlchandler(signal, frame):
     print
     print ENDC + "Terminating on Ctrl-C, closing threads for:",
     while queue:
         for ip, th in queue:
             print ip,
             try:
                 lock.acquire()
                 th.abort = True
                 lock.release()
             except RuntimeError:
                 pass
             queue.remove((ip,th))
     print
     pid = os.getpid()
     print "Finished closing threads."
     # suicide - it's the only way of preventing frequent hangup on sys.exit
     os.kill(pid, SIGTERM)
     os.kill(pid, SIGKILL)
     sys.exit(0)




More information about the Python-list mailing list