- 使用多进程充分利用cpu
- 使用异步编程
asyncio
import asyncio
import time
from abc import ABC
from concurrent.futures import ProcessPoolExecutor
from tornado import web, ioloop, genasync def async_task(name):print(f"start: {name}")st = int(time.time())time.sleep(3) await asyncio.sleep(3) result = f"task: {name}, start: {st}, end: {int(time.time())}"return resultdef run_async_task(name):return asyncio.run(async_task(name))class MainHandler(web.RequestHandler, ABC):executor = ProcessPoolExecutor() @gen.coroutinedef get(self):task_name = self.get_argument("task", "task-1")result = yield self.executor.submit(run_async_task, task_name)self.write(result)def make_app():return web.Application([(r"/", MainHandler),])if __name__ == '__main__':app = make_app()app.listen(8888)print("http://localhost:8888/?task=task-X")ioloop.IOLoop.current().start()