python多线程下信号处理程序示例
作者:雪峰流云 时间:2021-07-06 05:58:51
本文实例为大家分享了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终止多线程程序的问题解决
来源:https://blog.csdn.net/tao_627/article/details/46658721
标签:python,多线程,信号处理
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈python多线程和队列管理shell程序
2023-05-18 05:58:25
python使用Qt界面以及逻辑实现方法
2023-10-23 23:28:09
![](https://img.aspxhome.com/file/2023/4/87644_0s.png)
Python利用matplotlib实现制作动态条形图
2021-06-11 05:29:15
![](https://img.aspxhome.com/file/2023/9/82789_0s.gif)
如何使数据库中取出的数据保持原有格式
2008-11-27 16:16:00
Python中使用摄像头实现简单的延时摄影技术
2023-10-24 01:31:04
![](https://img.aspxhome.com/file/2023/8/70068_0s.gif)
mysql int范围与最大值分析
2012-03-26 18:24:00
python将天数转换为日期字符串的方法实例
2023-06-02 23:19:03
![](https://img.aspxhome.com/file/2023/0/84080_0s.png)
浅谈五大Python Web框架
2023-12-10 07:33:25
![](https://img.aspxhome.com/file/2023/6/77866_0s.png)
python实现邮箱发送信息
2023-02-25 15:11:51
网页设计标准尺寸参考
2007-12-29 20:42:00
Flash如何连接Mysql
2010-11-11 11:57:00
![](https://img.aspxhome.com/file/UploadPic/201011/11/20101111122935716s.jpg)
PHP对战ASP:这还值得讨论吗
2008-04-16 14:19:00
python+selenium 定位到元素,无法点击的解决方法
2022-02-01 12:29:52
CSS自适应宽度圆角按钮
2007-11-20 11:38:00
![](https://img.aspxhome.com/file/UploadPic/200711/20/20071120115213701s.gif)
用python求一个数组的和与平均值的实现方法
2021-01-10 20:11:24
Python3导入自定义模块的三种方法详解
2021-06-05 18:49:27
![](https://img.aspxhome.com/file/2023/3/86533_0s.png)
基于OpenCV的网络实时视频流传输的实现
2022-10-18 03:03:57
![](https://img.aspxhome.com/file/2023/9/90529_0s.png)
python-django中的APPEND_SLASH实现方法
2023-04-05 07:17:57
![](https://img.aspxhome.com/file/2023/7/95407_0s.jpg)
解读keras中的正则化(regularization)问题
2023-08-13 12:28:45
z-index在IE中的迷惑
2007-05-11 16:50:00