在tornado的异步http请求中托管一个阻塞的任务到线程池
实际代码中使用的是进程池,不过代码很简单,你可以将它替换为线程池。
1 from time import sleep 2 from tornado.httpserver import HTTPServer 3 from tornado.ioloop import IOLoop 4 from tornado.web import Application, asynchronous, RequestHandler 5 from multiprocessing.pool import ThreadPool 6 7 _workers = ThreadPool(10) 8 9 def run_background(func, callback, args=(), kwds={}): 10 def _callback(result): 11 IOLoop.instance().add_callback(lambda: callback(result)) 12 _workers.apply_async(func, args, kwds, _callback) 13 14 # blocking task like querying to MySQL 15 def blocking_task(n): 16 sleep(n) 17 return n 18 19 class Handler(RequestHandler): 20 @asynchronous 21 def get(self): 22 run_background(blocking_task, self.on_complete, (10,)) 23 24 def on_complete(self, res): 25 self.write("Test {0}<br/>".format(res)) 26 self.finish() 27 28 HTTPServer(Application([("/", Handler)],debug=True)).listen(8888) 29 IOLoop.instance().start()