原型 :
awaitable loop.run_in_executor(executor, func, *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))
本文介绍如何在Python的异步事件循环中利用线程池执行阻塞操作,如文件读取,以提高程序效率。通过示例展示了如何使用默认线程池及自定义线程池进行异步IO操作。
2万+

被折叠的 条评论
为什么被折叠?



