探寻python多线程ctrl+c退出问题解决方案


Posted in Python onOctober 23, 2014

场景:

经常会遇到下述问题:很多io busy的应用采取多线程的方式来解决,但这时候会发现python命令行不响应ctrl-c 了,而对应的java代码则没有问题:

public class Test {  

    public static void main(String[] args) throws Exception {  

  

        new Thread(new Runnable() {  

  

            public void run() {  

                long start = System.currentTimeMillis();  

                while (true) {  

                    try {  

                        Thread.sleep(1000);  

                    } catch (Exception e) {  

                    }  

                    System.out.println(System.currentTimeMillis());  

                    if (System.currentTimeMillis() - start > 1000 * 100) break;  

                }  

            }  

        }).start();  

  

    }  

}  

java Test

ctrl-c则会结束程序

而对应的python代码:

# -*- coding: utf-8 -*-  

import time  

import threading  

start=time.time()  

def foreverLoop():  

    start=time.time()  

    while 1:  

        time.sleep(1)  

        print time.time()  

        if time.time()-start>100:  

            break  

               

thread_=threading.Thread(target=foreverLoop)  

#thread_.setDaemon(True)  

thread_.start() 

python p.py

后ctrl-c则完全不起作用了。

不成熟的分析:

首先单单设置 daemon 为 true 肯定不行,就不解释了。当daemon为 false 时,导入python线程库后实际上,threading会在主线程执行完毕后,检查是否有不是 daemon 的线程,有的化就wait,等待线程结束了,在主线程等待期间,所有发送到主线程的信号也会被阻测,可以在上述代码加入signal模块验证一下:

def sigint_handler(signum,frame):    

    print "main-thread exit"  

    sys.exit()    

signal.signal(signal.SIGINT,sigint_handler) 

在100秒内按下ctrl-c没有反应,只有当子线程结束后才会出现打印 "main-thread exit",可见 ctrl-c被阻测了

threading 中在主线程结束时进行的操作:

_shutdown = _MainThread()._exitfunc  

def _exitfunc(self):  

        self._Thread__stop()  

        t = _pickSomeNonDaemonThread()  

        if t:  

            if __debug__:  

                self._note("%s: waiting for other threads", self)  

        while t:  

            t.join()  

            t = _pickSomeNonDaemonThread()  

        if __debug__:  

            self._note("%s: exiting", self)  

        self._Thread__delete()  

 

 对所有的非daemon线程进行join等待,其中join中可自行察看源码,又调用了wait,同上文分析 ,主线程等待到了一把锁上。

不成熟的解决:

只能把线程设成daemon才能让主线程不等待,能够接受ctrl-c信号,但是又不能让子线程立即结束,那么只能采用传统的轮询方法了,采用sleep间歇省点cpu吧:
 

# -*- coding: utf-8 -*-  

import time,signal,traceback  

import sys  

import threading  

start=time.time()  

def foreverLoop():  

    start=time.time()  

    while 1:  

        time.sleep(1)  

        print time.time()  

        if time.time()-start>5:  

            break  

              

thread_=threading.Thread(target=foreverLoop)  

thread_.setDaemon(True)  

thread_.start()  

  

#主线程wait住了,不能接受信号了  

#thread_.join()  

  

def _exitCheckfunc():  

    print "ok"  

    try:  

        while 1:  

            alive=False  

            if thread_.isAlive():  

                alive=True  

            if not alive:  

                break  

            time.sleep(1)    

    #为了使得统计时间能够运行,要捕捉  KeyboardInterrupt :ctrl-c        

    except KeyboardInterrupt, e:  

        traceback.print_exc()  

    print "consume time :",time.time()-start  

          

threading._shutdown=_exitCheckfunc 

   缺点:轮询总会浪费点cpu资源,以及battery.

有更好的解决方案敬请提出。

ps1: 进程监控解决方案 :

用另外一个进程来接受信号后杀掉执行任务进程,牛

# -*- coding: utf-8 -*-  

import time,signal,traceback,os  

import sys  

import threading  

start=time.time()  

def foreverLoop():  

    start=time.time()  

    while 1:  

        time.sleep(1)  

        print time.time()  

        if time.time()-start>5:  

            break  

  

class Watcher:  

    """this class solves two problems with multithreaded 

    programs in Python, (1) a signal might be delivered 

    to any thread (which is just a malfeature) and (2) if 

    the thread that gets the signal is waiting, the signal 

    is ignored (which is a bug). 

 

    The watcher is a concurrent process (not thread) that 

    waits for a signal and the process that contains the 

    threads.  See Appendix A of The Little Book of Semaphores. 

    http://greenteapress.com/semaphores/ 

 

    I have only tested this on Linux.  I would expect it to 

    work on the Macintosh and not work on Windows. 

    """  

  

    def __init__(self):  

        """ Creates a child thread, which returns.  The parent 

            thread waits for a KeyboardInterrupt and then kills 

            the child thread. 

        """  

        self.child = os.fork()  

        if self.child == 0:  

            return  

        else:  

            self.watch()  

  

    def watch(self):  

        try:  

            os.wait()  

        except KeyboardInterrupt:  

            # I put the capital B in KeyBoardInterrupt so I can  

            # tell when the Watcher gets the SIGINT  

            print 'KeyBoardInterrupt'  

            self.kill()  

        sys.exit()  

  

    def kill(self):  

        try:  

            os.kill(self.child, signal.SIGKILL)  

        except OSError: pass  

  

Watcher()              

thread_=threading.Thread(target=foreverLoop)  

thread_.start() 

 注意 watch()一定要放在线程创建前,原因未知。。。。,否则立刻就结束

Python 相关文章推荐
python操作日期和时间的方法
Mar 11 Python
在Mac OS上使用mod_wsgi连接Python与Apache服务器
Dec 24 Python
举例讲解Python中字典的合并值相加与异或对比
Jun 04 Python
Python 爬虫学习笔记之正则表达式
Sep 21 Python
Python 模拟购物车的实例讲解
Sep 11 Python
Windows下python3.6.4安装教程
Jul 31 Python
Python 面试中 8 个必考问题
Nov 16 Python
python3使用pandas获取股票数据的方法
Dec 22 Python
使用python判断jpeg图片的完整性实例
Jun 10 Python
python wxpython 实现界面跳转功能
Dec 17 Python
Tensorflow分批量读取数据教程
Feb 07 Python
ubuntu 安装pyqt5和卸载pyQt5的方法
Mar 24 Python
纯Python开发的nosql数据库CodernityDB介绍和使用实例
Oct 23 #Python
Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子
Oct 23 #Python
使用Python开发windows GUI程序入门实例
Oct 23 #Python
手动实现把python项目发布为exe可执行程序过程分享
Oct 23 #Python
python文件操作整理汇总
Oct 21 #Python
Python中input和raw_input的一点区别
Oct 21 #Python
Python中if __name__ == "__main__"详细解释
Oct 21 #Python
You might like
php出现Cannot modify header information问题的解决方法大全
2008/04/09 PHP
php注销代码(session注销)
2012/05/31 PHP
php IP转换整形(ip2long)的详解
2013/06/06 PHP
laravel 之 Eloquent 模型修改器和序列化示例
2019/10/17 PHP
PHP pthreads v3下worker和pool的使用方法示例
2020/02/21 PHP
javascript实现div浮动在网页最顶上并带关闭按钮效果实例
2013/08/13 Javascript
js+css实现select的美化效果
2016/03/24 Javascript
JS创建事件的三种方法(实例代码)
2016/05/12 Javascript
NodeJs读取JSON文件格式化时的注意事项
2016/09/25 NodeJs
EditPlus 正则表达式 实战(3)
2016/12/15 Javascript
Node.js Mongodb 密码特殊字符 @的解决方法
2017/04/11 Javascript
微信小程序开发图片拖拽实例详解
2017/05/05 Javascript
Bootstrap 表单验证formValidation 实现远程验证功能
2017/05/17 Javascript
vue2.0 父组件给子组件传递数据的方法
2018/01/15 Javascript
微信实现自动跳转到用其他浏览器打开指定APP下载
2019/02/15 Javascript
webpack 处理CSS资源的实现
2019/09/27 Javascript
vuex + keep-alive实现tab标签页面缓存功能
2019/10/17 Javascript
Vue-cli打包后部署到子目录下的路径问题说明
2020/09/02 Javascript
Python实现telnet服务器的方法
2015/07/10 Python
Python+PIL实现支付宝AR红包
2018/02/09 Python
python将文本分每两行一组并保存到文件
2018/03/19 Python
python对html过滤处理的方法
2018/10/21 Python
python 解决flask uwsgi 获取不到全局变量的问题
2019/12/22 Python
pytorch载入预训练模型后,实现训练指定层
2020/01/06 Python
关于pytorch中全连接神经网络搭建两种模式详解
2020/01/14 Python
python为Django项目上的每个应用程序创建不同的自定义404页面(最佳答案)
2020/03/09 Python
基于python实现复制文件并重命名
2020/09/16 Python
Canvas 文字碰撞检测并抽稀的方法
2019/05/27 HTML / CSS
物业管理公司实习生自我鉴定
2013/09/19 职场文书
毕业生就业推荐信范文
2013/12/01 职场文书
财务担保书范文
2014/04/02 职场文书
《放飞蜻蜓》教学反思
2014/04/27 职场文书
个人授权委托书范本
2014/09/14 职场文书
大学生入党自荐书
2015/03/05 职场文书
2019经典广告词集锦!
2019/07/02 职场文书
Flutter集成高德地图并添加自定义Maker的实践
2022/04/07 Java/Android