如何在键盘中断时杀死子线程

时间:2014-04-10 11:19:36

标签: python multithreading cherrypy

cherrypy服务器启动如下:

root = Root()
cherrypy.engine.loggingPlugin = LoggerPlugin(cherrypy.engine)
cherrypy.engine.loggingPlugin.init(root.grapher.writequeue)
cherrypy.engine.loggingPlugin.subscribe()
cherrypy.quickstart(Root(), "/", conf)

LoggerPlugin定义为:

class LoggerPlugin(plugins.SimplePlugin):
"""Intended to catch the stop signal and terminate WriteLog"""
def init(self, queue):
    self.logger = WriteLog("viewerlog.log", queue, 2)

def start(self):
    self.logger.start()

def stop(self):
    print "Exit"
    self.logger.stop()
    print "Exited"

最后,WriteLog是:

class WriteLog (threading.Thread):
def __init__(self, filename, queue, freq):
    self.out = open(filename, "a+")
    self.queue = queue
    self.freq = freq # The time to sleep after every empty queue, in seconds
    self.exit = False
    super(WriteLog, self).__init__()

def stop(self):
    self.exit = True

def run(self):
    while True:
        if self.exit:
            sys.exit(0)

        """ do stuff """

当我按下Ctrl + C时,控制台看起来像:

 ENGINE Bus STOPPING
 ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer shut down
 ENGINE Stopped thread '_TimeoutMonitor'.
 ENGINE Bus STOPPED
 ENGINE Bus EXITING
 ENGINE Bus EXITED
 ENGINE Waiting for child threads to terminate...
 ENGINE Waiting for thread Thread-1.

之后没有任何事情发生。

因为WriteLog是唯一产生的线程,所以它应该是罪魁祸首。即使在WriteLog.exit设置为True时应调用sys.exit(),也不会发生这种情况。

1 个答案:

答案 0 :(得分:0)

嗯,你使用的是什么版本的python和cherrypy?我运行了这段代码,线程正确终止。

import cherrypy 
import sys
import threading            

class Root(object):
    def asdf(self):
        return 'hi'

    def grapher(self):
        return 'hi'

class LoggerPlugin(cherrypy.process.plugins.SimplePlugin):
    """Intended to catch the stop signal and terminate WriteLog"""
    def init(self, queue):
        self.logger = WriteLog("viewerlog.log", queue, 2)

    def start(self):
        self.logger.start()

    def stop(self):
        print("Exit")
        self.logger.stop()
        print("Exited")

class WriteLog (threading.Thread):
    def __init__(self, filename, queue, freq):
        self.out = open(filename, "a+")
        self.queue = queue
        self.freq = freq # The time to sleep after every empty queue, in seconds
        self.exit = False
        super(WriteLog, self).__init__()

    def stop(self):
        print("WriteLog Exited")
        self.exit = True

    def run(self):
        while True:
            if self.exit:
                sys.exit(0)

            """ do stuff """

root = Root()
cherrypy.engine.loggingPlugin = LoggerPlugin(cherrypy.engine)
cherrypy.engine.loggingPlugin.init(root.grapher)
cherrypy.engine.loggingPlugin.subscribe()
cherrypy.quickstart(Root(), "/")

这是我的输出......

[user@dev Scratch_Pad]$ /opt/python3/bin/python3.3 webapp.py
[10/Apr/2014:08:28:26] ENGINE Listening for SIGTERM.
[10/Apr/2014:08:28:26] ENGINE Listening for SIGHUP.
[10/Apr/2014:08:28:26] ENGINE Listening for SIGUSR1.
[10/Apr/2014:08:28:26] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[10/Apr/2014:08:28:26] ENGINE Started monitor thread 'Autoreloader'.
[10/Apr/2014:08:28:26] ENGINE Started monitor thread '_TimeoutMonitor'.
[10/Apr/2014:08:28:27] ENGINE Serving on 127.0.0.1:8080
[10/Apr/2014:08:28:27] ENGINE Bus STARTED
^C[10/Apr/2014:08:28:29] ENGINE Keyboard Interrupt: shutting down bus
[10/Apr/2014:08:28:29] ENGINE Bus STOPPING
[10/Apr/2014:08:28:29] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('127.0.0.1', 8080)) shut down
[10/Apr/2014:08:28:29] ENGINE Stopped thread 'Autoreloader'.
Exit
WriteLog Exited
Exited
[10/Apr/2014:08:28:29] ENGINE Stopped thread '_TimeoutMonitor'.
[10/Apr/2014:08:28:29] ENGINE Bus STOPPED
[10/Apr/2014:08:28:29] ENGINE Bus EXITING
[10/Apr/2014:08:28:29] ENGINE Bus EXITED
[10/Apr/2014:08:28:29] ENGINE Waiting for child threads to terminate...
[10/Apr/2014:08:28:29] ENGINE Waiting for thread Thread-1.

这里的过程消失了......

500       5526  5452 99 08:23 pts/1    00:00:42 /opt/python3/bin/python3.3 webapp.py

我相信这个帖子并没有证实它已经消失了。你还在看这个过程吗?

希望这有帮助!