Skip to content

Instantly share code, notes, and snippets.

@dongchao-cn
Created October 7, 2013 14:55
Show Gist options
  • Save dongchao-cn/6869344 to your computer and use it in GitHub Desktop.
Save dongchao-cn/6869344 to your computer and use it in GitHub Desktop.
#!/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=7000, help="run on the given port", type=int)
class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(10)
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
start = time.time()
res = yield self.sleep()
self.write("when i sleep %f s" % (time.time() - start))
self.finish()
@run_on_executor
def sleep(self):
time.sleep(5)
return 5
class JustNowHandler(tornado.web.RequestHandler):
def get(self):
self.write("i hope just now see you")
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r"/sleep", SleepHandler), (r"/justnow", JustNowHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
@shajiquan
Copy link

Thanks。

@Chichele
Copy link

请问@run_on_executor是如何与executor = ThreadPoolExecutor(10)联系起来的?我看源码不大明白run_on_executor是在哪里调用executor的。
只能找到一句future = self.executor.submit(fn, self, *args, **kwargs),难道意思就是只要ThreadPoolExecutor(10)的返回值保存在名字为executor的变量就可以了吗?


是的,确实是这样,我明白了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment