from abc import ABC
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from tornado.concurrent import run_on_executor
import tornado.web
import tornado.gen
import time

class AsyncUtils:
    def __init__(self, num_worker=10):
        self.io_loop = IOLoop.current()
        self.executor = ThreadPoolExecutor(num_worker)

    @run_on_executor
    def cmd(self, func, *args, **kwargs):
        res = func(*args, **kwargs)
        return res



_ASYNC = AsyncUtils(5)  # 线程池大小为5


class MainHandler(tornado.web.RequestHandler, ABC):
    def get(self):
        self.write('Hello, world')


class MainAsyncHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        res = yield _ASYNC.cmd(time.sleep, 10)  # sleep 10s
        self.write('Hello, world2')


application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/async", MainAsyncHandler),
])

if __name__ == '__main__':
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()