从线程停止龙卷风 [英] Stopping tornado from thread

查看:53
本文介绍了从线程停止龙卷风的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行龙卷风,并从一个单独的线程监控各种数据源等.在这种情况下,如果用户关闭浏览器,则关闭 Web 服务器很重要.我只是依靠来自浏览器的心跳请求,然后想要停止龙卷风 ioloop.事实证明这非常困难:

I'm running tornado, and monitoring various data sources etc from a separate thread. It's important in this instance to close the web server if the user closes the browser. I'm simply relying on heartbeat requests from the browser, and then want to stop the tornado ioloop. This is proving very difficult:

# Start the main processing loop
mLoop = threading.Thread(target = mainLoop, args=())
mLoop.start()

# Set up webserver
parser = argparse.ArgumentParser(description="Starts a webserver.")
parser.add_argument("--port", type=int, default=8000, help="The port")
args = parser.parse_args()

handlers = [(r"/", IndexHandler), (r"/websocket", WebSocket),
            (r'/static/(.*)', tornado.web.StaticFileHandler,
             {'path': os.path.normpath(os.path.dirname(__file__))})]
application = tornado.web.Application(handlers)
application.listen(args.port)

webbrowser.open("http://localhost:%d/" % args.port, new=2)

tornado.ioloop.IOLoop.instance().start()

在某些情况下,主循环需要停止龙卷风,但它无法访问 ioloop 来调用 IOLoop.stop()(或者可能更好的 IOLoop.instance.stop()),因为它不是启动的线程它.

The main loop needs to, in certain conditions, stop tornado, but it can't access the ioloop to call IOLoop.stop() (or probably better IOLoop.instance.stop()) because it's not the thread which started it.

实现这一目标的最佳方法是什么?

What's the best way to accomplish this?

推荐答案

application.listen 返回一个 HTTPServer 实例,您可以停止它,关闭套接字/端口.然后关闭IOLoop实例.

application.listen returns an HTTPServer instance which you can stop, closing the socket/port. Then close the IOLoop instance.

from tornado.web import Application
from tornado.ioloop import IOLoop

# starting
application = Application(...)
server = application.listen(args.port)
# depends on your use-case
eventLoopThread = Thread(target=IOLoop.current().start)
eventLoopThread.daemon = True
eventLoopThread.start()

# stopping
server.stop()
IOLoop.current().stop()

这篇关于从线程停止龙卷风的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆