探寻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压缩和解压缩zip文件
Feb 14 Python
深入解析Python中的集合类型操作符
Aug 19 Python
python处理xml文件的方法小结
May 02 Python
Python中字典和集合学习小结
Jul 07 Python
Python实现将json文件中向量写入Excel的方法
Mar 26 Python
对django中render()与render_to_response()的区别详解
Oct 16 Python
python gdal安装与简单使用
Aug 01 Python
详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决
Aug 27 Python
Django 框架模型操作入门教程
Nov 05 Python
python+selenium+PhantomJS抓取网页动态加载内容
Feb 25 Python
tensorflow模型转ncnn的操作方式
May 25 Python
python脚本第一行如何写
Aug 30 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后端方法)
2016/02/03 PHP
一个tab标签切换效果代码
2009/03/27 Javascript
javascript之学会吝啬 精简代码
2010/04/25 Javascript
JavaScript接口实现代码 (Interfaces In JavaScript)
2010/06/11 Javascript
js日期相关函数总结分享
2013/10/15 Javascript
JS页面延迟执行一些方法(整理)
2013/11/11 Javascript
JavaScript模板引擎用法实例
2015/07/10 Javascript
ES6概念 Symbol toString()方法
2016/12/25 Javascript
Vue2学习笔记之请求数据交互vue-resource
2017/02/23 Javascript
JS HTML图片显示Canvas 压缩功能
2017/07/21 Javascript
如何用JavaScript实现功能齐全的单链表详解
2019/02/11 Javascript
js实现全选和全不选
2020/07/28 Javascript
[01:03]DOTA2新的征程 你的脚印值得踏上
2014/08/13 DOTA
[38:32]DOTA2上海特级锦标赛A组资格赛#2 Secret VS EHOME第二局
2016/02/26 DOTA
Python中给List添加元素的4种方法分享
2014/11/28 Python
python 换位密码算法的实例详解
2017/07/19 Python
详解python基础之while循环及if判断
2017/08/24 Python
python numpy和list查询其中某个数的个数及定位方法
2018/06/27 Python
tensorflow 恢复指定层与不同层指定不同学习率的方法
2018/07/26 Python
对Python 内建函数和保留字详解
2018/10/15 Python
Window环境下Scrapy开发环境搭建
2018/11/18 Python
python按修改时间顺序排列文件的实例代码
2019/07/25 Python
wxPython多个窗口的基本结构
2019/11/19 Python
Python标准库itertools的使用方法
2020/01/17 Python
python为Django项目上的每个应用程序创建不同的自定义404页面(最佳答案)
2020/03/09 Python
python爬取”顶点小说网“《纯阳剑尊》的示例代码
2020/10/16 Python
五分钟学会怎么用Pygame做一个简单的贪吃蛇
2021/01/06 Python
CSS3 rgb and rgba(透明色)的使用详解
2020/09/25 HTML / CSS
《最后的姿势》教学反思
2014/02/27 职场文书
竞聘书怎么写,如何写?
2014/03/31 职场文书
离婚协议书应该怎么写
2014/10/12 职场文书
品质保证书格式
2015/02/28 职场文书
学生乘坐校车安全责任书
2015/05/11 职场文书
2016年员工年度考核评语
2015/12/02 职场文书
Java中try catch处理异常示例
2021/12/06 Java/Android
Go Grpc Gateway兼容HTTP协议文档自动生成网关
2022/06/16 Golang