本篇文章为大家展示了怎么在python中实现多线程下信号处理,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。
思路
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中实现多线程下信号处理,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。