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

标签 python python-asyncio

在 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/

    相关文章:

    python - 如何以通用换行模式访问上传的文件?

    python - 在python中复制一个列表

    python - asyncio 中的坏锁优化

    python - Asyncio 未并行运行 Aiohttp 请求

    python - 表单验证失败后重定向

    python - 不要使用 json.dumps 引用某些字符串

    python - 延迟等待异步 ndb 调用的最漂亮的方法是什么?

    python3 asyncio start_unix_server 权限

    python - 哪个协程是顺序的?

    python - aiohttp:response.status 什么时候可用?