在协程中总会使用到同步IO

来源:11-5 通过aiofiles保存图片文件-2

微微视界123

2019-07-31

老师,请问一下,我在项目中使用的FastDFS实现的文件上传和下载,这样就没法使用异步了,有什么方案可以解决么?

写回答

2回答

bobby

2019-08-01

import time
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor   
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(10)        
        return i    
        
    @tornado.gen.coroutine
    def get(self, idx):        """ Request that asynchronously calls background task. """
        res = yield self.background_task(idx)        
        self.write(res)


0
2
bobby
回复
微微视界123
能否将代码格式化一下 你不要在回复中写,你直接在评论中回复就可以格式化了
2019-08-05
共2条回复

bobby

2019-07-31

tornado启动的时候有线程池 https://gist.github.com/methane/2185380 可以参照这个将阻塞任务扔到线程池中去运行

0
1
微微视界123
老师,这个地址打不开啊
2019-08-01
共1条回复

Tornado从入门到进阶 打造支持高并发的技术论坛

异步IO并发编程/Form,ORM/aiomysql、peewee-async/epoll

595 学习 · 350 问题

查看课程