CherryPy 等待额外的线程结束,稍后停止

CherryPy waits for extra thread to end that is stopped later

我正在构建一个使用 CherryPy 为 REST API 提供服务的应用程序,以及另一个执行后台工作的线程(实际上,它从串行端口读取数据)。

import cherrypy
import threading

class main:
    @cherrypy.expose
    def index(self):
        return "Hello World."

def run():
   while running == True:
       # read data from serial port and store in a variable

running = True
t = threading.Thread(target = run)
t.start()

if __name__ == '__main__':
    cherrypy.quickstart(main())

running = False

api.pc_main()run 都可以正常工作。问题是,我使用 running 布尔值来停止我的线程,但是那段代码永远不会到达,因为当我按下 Ctrl-C 时,CherryPy 会等待该线程完成。我实际上必须使用 kill -9 来停止进程。

我通过将我的线程设为 CherryPy 插件来修复它。我使用了在这里找到的代码:Why is CTRL-C not captured and signal_handler called?

from cherrypy.process.plugins import SimplePlugin

class myplugin(SimplePlugin):
    running = False
    thread = None

    def __init__(self, bus):
        SimplePlugin.__init__(self, bus)

    def start(self):
        print "Starting thread."
        self.running = True
        if not self.thread:
            self.thread = threading.Thread(target = self.run)
            self.thread.start()

    def stop(self):
        print "Stopping thread."
        self.running = False

        if self.thread:
            self.thread.join()
            self.thread = None


    def run(self):
        while self.running == True:
            print "Thread runs."
            time.sleep(1)

然后在主脚本中:

if __name__ == '__main__':
    mythread(cherrypy.engine).subscribe()
    cherrypy.quickstart(main())