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多线程下信号处理程序示例

参考文献

Python中用Ctrl+C终止多线程程序的问题解决

相关推荐