run_in_executor

本文介绍如何在Python的异步事件循环中利用线程池执行阻塞操作,如文件读取,以提高程序效率。通过示例展示了如何使用默认线程池及自定义线程池进行异步IO操作。

 

原型 :

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值