在tornado的异步http请求中托管一个阻塞的任务到线程池

Comments(2)


Posted on 2012-12-17 17:43:17 tornado


实际代码中使用的是进程池,不过代码很简单,你可以将它替换为线程池。

from time import sleep
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, asynchronous, RequestHandler
from multiprocessing.pool import ThreadPool
 
_workers = ThreadPool(10)
 
def run_background(func, callback, args=(), kwds={}):
    def _callback(result):
        IOLoop.instance().add_callback(lambda: callback(result))
    _workers.apply_async(func, args, kwds, _callback)
 
def blocking_task(n):
    sleep(n)
    return n
 
class Handler(RequestHandler):
    @asynchronous
    def get(self):
        run_background(blocking_task, self.on_complete, (10,))

    def on_complete(self, res):
        self.write("Test {0}<br/>".format(res))
        self.finish()
 
HTTPServer(Application([("/", Handler)],debug=True)).listen(8888)
IOLoop.instance().start()
前一篇: python的参数传递机制 后一篇: tornado长连接断开的处理机制

Captcha:
验证码

Email:

Content: (Support Markdown Syntax)


OKBet  2023-07-11 09:34:51 From 127.0.0.1

Hi just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. OKBet philippines


ok  2023-07-15 05:39:08 From 127.0.0.1

Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon!

My site: Stefanos Tsitsipas Third Seed