【发布时间】:2019-12-06 04:54:07
【问题描述】:
在 Python docs 中,它声明:
应用程序开发人员通常应该使用高级异步 函数,例如 asyncio.run(),并且应该很少需要引用 循环对象或调用它的方法。 本部分主要面向需要更好地控制事件循环行为的低级代码、库和框架的作者。
同时使用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()会帮我关闭循环? - 是否同时使用
asyncio和threadpoolexecutor,这是您需要更好地控制事件循环的情况之一?是否可以同时使用asyncio和threadpoolexecutor而无需引用loop?
【问题讨论】:
标签: python python-asyncio