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

时间:2017-04-29 14:37:53

标签: python multithreading cherrypy

我正在构建一个使用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来停止这个过程。

1 个答案:

答案 0 :(得分:1)

我通过使我的线程成为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())