gpt4 book ai didi

python - 当需要使用AsyncIO和ThreadPoolExecutor时,是否需要手动调用loop.close()?

转载 作者:行者123 更新时间:2023-12-03 14:42:59 25 4
gpt4 key购买 nike

在 Python 中 docs , 它指出:

Application developers should typically use the high-level asyncio functions, such as asyncio.run(), and should rarely need to reference the loop object or call its methods. This section is intended mostly for authors of lower-level code, libraries, and frameworks, who need finer control over the event loop behavior.



当同时使用 async和一个 threadpoolexecutor ,如示例代码所示(来自文档):
import asyncio
import concurrent.futures

def blocking_io():
# File operations (such as logging) can block the
# event loop: run them in a thread pool.
with open('/dev/urandom', 'rb') as f:
return f.read(100)

async def main():
loop = asyncio.get_running_loop()

# 2. Run in a custom thread pool:
with concurrent.futures.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(
pool, blocking_io)
print('custom thread pool', result)

asyncio.run(main())
  • 我需要打电话loop.close() ,或者 asyncio.run()为我关闭循环?
  • 两者都使用 asynciothreadpoolexecutor一起,您需要更好地控制事件循环的那些情况之一?可以同时使用,asynciothreadpoolexecutor一起完成而不引用 loop ?
  • 最佳答案

    对于问题#1,coroutines and tasks您引用的事件循环文档中链接的文档表明 asyncio.run 关闭了循环:

    asyncio.run(coro, *, debug=False)

    Execute the coroutine coro and return the result.

    This function runs the passed coroutine, taking care of managing the asyncio event loop and finalizing asynchronous generators.

    This function cannot be called when another asyncio event loop is running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.



    对于#2,将 get_running_loop 与 ThreadExecutor 一起使用是一种在不阻塞 OS 线程的情况下运行阻塞代码的方法。在 Developing with asyncio ,它们表明:

    The loop.run_in_executor() method can be used with a concurrent.futures.ThreadPoolExecutor to execute blocking code in a different OS thread without blocking the OS thread that the event loop runs in.



    这是他们在事件文档中给出的关于调用低级方法的一般警告的一个异常(exception)。所以问题#2 的答案是肯定的,这是一种需要少量更精细控制才能执行处理异步场景中阻塞代码的方法的情况。

    关于python - 当需要使用AsyncIO和ThreadPoolExecutor时,是否需要手动调用loop.close()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59199218/

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