下面是一个网上转载的实现思路,经过验证,发现是可行的,就记录下来。
思路
python多线程中要响应Ctrl+C的信号以杀死整个进程,需要:
1.把所有子线程设为Daemon;
2.使用isAlive()函数判断所有子线程是否完成,而不是在主线程中用join()函数等待完成;
3.写一个响应Ctrl+C信号的函数,修改全局变量,使得各子线程能够检测到,并正常退出。
源码
#!/usr/bin/env python
#encoding: utf-8
#filename: signal_demo.py
import threading, signaldef do_job(i, step):global exitedidx = iwhile not exited:if(idx < 10000000):print 'thread[%d]: idx=%d' % (i, idx)idx = idx + stepelse:breakif exited:print 'receive a signal to exit, thread[%d] stop.' % ielse:print 'thread[%d] complete.' % idef sig_handler(sig, frame):global exitedexited = Trueprint 'receive a signal %d, exited=%d' % (sig, exited)def main():#set signal handlersignal.signal(signal.SIGTERM, sig_handler)signal.signal(signal.SIGINT, sig_handler)pool = []pool_size = 50for i in range(pool_size):t = threading.Thread(target = do_job, args = (i, pool_size))t.setDaemon(True)pool.append(t)t.start()while 1:alive = Falsefor i in range(pool_size):alive = alive or pool[i].isAlive()if alive == True:breakif not alive:breakif __name__ == '__main__':exited = Falsemain()
命令行运行
python signal_demo.py
截图
参考文献
[1].http://www.jb51.net/article/35165.htm