栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中为非异步函数使用asyncio吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中为非异步函数使用asyncio吗?

如果某个函数在本质上是阻塞的而不是异步的,则在

asyncio
事件循环内运行该函数的唯一正确方法是使用run_in_executor在线程内运行该函数:

# Our example blocking functionsimport timedef queryFoo():    time.sleep(3)    return 'foo'def queryBar():    time.sleep(3)    return 'bar'# Run them using asyncioimport asynciofrom concurrent.futures import ThreadPoolExecutor_executor = ThreadPoolExecutor(10)async def in_thread(func):    loop = asyncio.get_event_loop()    return await loop.run_in_executor(_executor, func)async def main():    results = await asyncio.gather(        in_thread(queryFoo),         in_thread(queryBar),    )    print(results)if __name__ == "__main__":    loop = asyncio.get_event_loop()    try:        loop.run_until_complete(main())    finally:        loop.run_until_complete(loop.shutdown_asyncgens())        loop.close()

它确实起作用。

但是,如果您想避免使用线程的唯一方法是-重写

queryFoo
/
queryBar
本质上是异步的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号