Skip to content

Instantly share code, notes, and snippets.

@zooyf
Created September 22, 2018 08:03
Show Gist options
  • Save zooyf/4bbbf310bf9866916b01812b76aab4c4 to your computer and use it in GitHub Desktop.
Save zooyf/4bbbf310bf9866916b01812b76aab4c4 to your computer and use it in GitHub Desktop.
tornado concurrent
#!/bin/env python
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
# 这个并发库在python3自带;在python2需要安装sudo pip install futures
from tornado.options import define, options
define("port", default=8002, help="run on the given port", type=int)
import time
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor # `pip install futures` for python2
MAX_WORKERS = 4
class Handler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
@run_on_executor
def background_task(self, i):
""" This will be executed in `executor` pool. """
time.sleep(float(i))
return i
@tornado.gen.coroutine
def get(self, idx):
""" Request that asynchronously calls background task. """
res = yield self.background_task(idx)
self.write(res)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r"/sleep/(.+)", Handler), ])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment