run_in_executor

版权声明: https://blog.csdn.net/dashoumeixi/article/details/85006168

原型 :

awaitable loop.run_in_executor(executorfunc*args

参数 : executor 可以是  ThreadPoolExecutor / ProcessPool  , 如果是None 则使用默认线程池

可使用 yield from 或 await 挂起函数

作用  : 例如在异步事件循环中 写文件, 这种那么慢的操作交给线程去做

完整例子: python 异步下载 完整例子

例子:

def block_func():
    with open("c:/PDFXVwer.zip",'rb') as fd:
        return fd.read(500)

async  def todo(lp:asyncio.AbstractEventLoop):
    readed = await lp.run_in_executor(None,block_func) # 默认线程池
    print("readed:",readed)


    with futures.ThreadPoolExecutor() as ex:
        readed = await lp.run_in_executor(ex,block_func)  # 自己创建一个线程池让事件循环调用
        print("readed :", readed)

lp = asyncio.get_event_loop()

lp.run_until_complete(todo(lp))

猜你喜欢

转载自blog.csdn.net/dashoumeixi/article/details/85006168
run