gpt4 book ai didi

python - 在 Python 中使用 asyncio 实现非异步函数?

转载 作者:行者123 更新时间:2023-12-02 09:42:06 27 4
gpt4 key购买 nike

假设有一个库可以进行各种数据库查询:

import time

def queryFoo():
time.sleep(4)
return "foo"

def queryBar():
time.sleep(4)
return "bar"

我想同时执行这两个查询,而无需将 async 添加到方法签名或添加装饰器。这些函数根本不应该依赖于 asyncio。

asyncio 中利用这些非异步函数的最佳方式是什么?

我正在寻找以下形式的东西:

#I need an 'asyncWrapper'

results = asyncio.gather(asyncWrapper(queryFoo()), asyncWrapper(queryBar()))

预先感谢您的考虑和回复。

最佳答案

如果某些函数本质上是阻塞的且不是异步的,则在 asyncio 事件循环内运行它的唯一正确方法是使用 run_in_executor 在线程内运行它。 :

# Our example blocking functions
import time


def queryFoo():
time.sleep(3)
return 'foo'


def queryBar():
time.sleep(3)
return 'bar'


# Run them using asyncio
import asyncio
from 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 重写为本质上的异步。

关于python - 在 Python 中使用 asyncio 实现非异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com