【问题标题】:CherryPy waits for extra thread to end that is stopped laterCherryPy 等待额外线程结束,稍后停止
【发布时间】:2017-09-27 13:23:23
【问题描述】:

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

【问题讨论】:

  • 由于这种情况,全局变量总是一个坏主意
  • @AzatIbrakov 只是为了举例。实际代码使用具有running 布尔值的类。
  • 它不会改变任何东西,你只是将变量从全局范围移动到类范围
  • @AzatIbrakov 好吧,它确实改变了一些东西。它不再是全球性的。更不用说,这不是我的问题的重点。
  • 有没有什么方法可以不用线程?

标签: python multithreading cherrypy


【解决方案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())

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 2012-07-13
    • 2021-11-03
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多