繁体   English   中英

Tornado.web.RequestHandler的简单多线程示例

[英]simple multithreading example with tornado.web.RequestHandler

我有一个mysterious_library ,提供同步功能query_resource_for_a_long_time

然后,我有下面的代码应该异步获取资源:

import tornado.ioloop
import tornado.web

import threading
from mysterious_library import query_resource_for_a_long_time, ResourceNotFoundException

def resource_fetcher(set_status, finish):
    try:
        resource = query_resource_for_a_long_time()

    except ResourceNotFoundException:
        tornado.ioloop.IOLoop.instance().add_callback(set_status, 404)
        tornado.ioloop.IOLoop.instance().add_callback(finish, 'not found')

    else:
        tornado.ioloop.IOLoop.instance().add_callback(set_status, 200)
        tornado.ioloop.IOLoop.instance().add_callback(finish, str(resource))

class Handler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        threading.Thread(
            target=resource_fetcher,
            args=[self.set_status, self.finish]
        ).start()


tornado.web.Application([
    (r'.*', Handler),
]).listen(8765)
tornado.ioloop.IOLoop.instance().start()

但是,尽管该函数在单独的线程中运行,但似乎该过程被阻塞,直到query_resource_for_a_long_time返回。

我是龙卷风的新手,我想知道是否可以同时处理这些请求。

是的,按照说明使用ThreadPoolExecutor:

http://www.tornadoweb.org/en/stable/guide/coroutines.html#calling-blocking-functions

请注意,在测试时,只能一次从浏览器运行几个查询:

http://www.tornadoweb.org/en/stable/faq.html#my-code-is-asynchronous-but-it-s-not-running-in-parallel-in-two-browser-tabs

...因此,如果您想证明自己可以从Tornado一次在多个线程中运行神秘的长期运行函数,请尝试使用wget或curl。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM