python多线程下信号处理程序示例
本文实例为大家分享了python多线程下信号处理程序示例的具体代码,供大家参考,具体内容如下
下面是一个网上转载的实现思路,经过验证,发现是可行的,就记录下来。
思路
python多线程中要响应Ctrl+C的信号以杀死整个进程,需要:
1.把所有子线程设为Daemon;
2.使用isAlive()函数判断所有子线程是否完成,而不是在主线程中用join()函数等待完成;
3.写一个响应Ctrl+C信号的函数,修改全局变量,使得各子线程能够检测到,并正常退出。
源码
#!/usr/bin/env python #encoding: utf-8 #filename: signal_demo.py import threading, signal def do_job(i, step): global exited idx = i while not exited: if(idx < 10000000): print 'thread[%d]: idx=%d' % (i, idx) idx = idx + step else: break if exited: print 'receive a signal to exit, thread[%d] stop.' % i else: print 'thread[%d] complete.' % i def sig_handler(sig, frame): global exited exited = True print 'receive a signal %d, exited=%d' % (sig, exited) def main(): #set signal handler signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) pool = [] pool_size = 50 for 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 = False for i in range(pool_size): alive = alive or pool[i].isAlive() if alive == True: break if not alive: break if __name__ == '__main__': exited = False main()
命令行运行
python signal_demo.py
截图
参考文献
Python中用Ctrl+C终止多线程程序的问题解决
相关推荐
farewellpoem 2020-11-09
lhtzbj 2020-08-13
learnpy 2020-07-19
kyelu 2020-07-09
举 2020-06-14
haokele 2020-05-31
fengling 2020-05-31
maimang00 2020-05-30
坚持是一种品质 2020-05-28
laityc 2020-05-27
jling 2020-05-19
YENCSDN 2020-05-14
singer 2020-04-30
举 2020-04-29
学习备忘录 2020-04-20
CloudXli 2020-04-07
瓜牛呱呱 2020-11-12
starinshy 2020-11-10
cuiweisaidelike 2020-08-02
comeonxueRong 2020-08-02
yunfeitian 2020-07-05
zhoujiyu 2020-06-28