【问题标题】:Can't get Tornado webserver to thread code无法让 Tornado 网络服务器线程代码
【发布时间】:2011-06-02 01:54:41
【问题描述】:

刚开始使用 Tornado,不知道我做错了什么,但我根本无法让它线程化,这是我正在测试的代码。

    import tornado.ioloop
    import tornado.web
    import time
    from threading import Timer

    class MainHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):
            t = Timer(5.0, self.on_response)
            t.start()
            print 'thread started'

        def on_response(self):
            self.write(str(time.time()))
            self.finish()

    application = tornado.web.Application([
        (r"/", MainHandler),
    ])

    if __name__ == "__main__":
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()

如果我运行它,它可以工作,但它会阻塞整个网络服务器 5 秒,所以如果我尝试快速连续两次加载此页面,它将打印“线程启动”,等待 5 秒,第一个浏览器将加载,然后它会再次打印“线程启动”,再等待 5 秒,然后将页面发送给第二个浏览器,总共需要 10 秒。

即使从 tornado 网站运行非阻塞示例,我也遇到了这个问题。有什么想法吗?

尝试使用 python 2.6 和 2.7,来自 easy_install 的 Tornado 1.2.1。

【问题讨论】:

    标签: python multithreading tornado


    【解决方案1】:

    您发布的代码在 Snow Leopard 上使用 Python 2.6.1 对我来说符合预期。你试过用 curl 测试吗?:

    curl --no-buffer localhost:8888 & curl --no-buffer localhost:8888
    

    【讨论】:

    • 奇怪,如果我使用 curl 它工作正常。但是如果我两次使用同一个网络浏览器,比如 chrome 中的 2 个选项卡,或者 Firefox 中的 2 个选项卡,我就会遇到这个问题。但是Firefox中的一个选项卡和chrome中的一个选项卡很好。我想知道是什么原因造成的。
    【解决方案2】:
    1. 我尝试在 2 个选项卡中使用 chrome。这大约需要 10 秒。
    2. 我尝试在 2 个标签中使用 IE9。这大约需要 5 秒。
    3. 编写一个网页,向该URL一个一个发送2个AJAX请求,(带有无意义的查询参数,避免浏览器缓存),大约需要5秒。
    4. 如您所见,curl 也可以在 5 秒左右工作。

    所以,这可能是浏览器/客户端指定的行为让我们感到困惑。

    【讨论】:

    • 虽然 Tornado 是一个单线程,但它是一个事件循环。第二个请求当然可以在第一个完成之前开始。
    猜你喜欢
    • 2011-07-01
    • 2011-12-12
    • 1970-01-01
    • 2018-09-08
    • 2012-11-30
    • 1970-01-01
    • 2011-07-19
    • 2023-03-15
    相关资源
    最近更新 更多