gpt4 book ai didi

python-asyncio - run_in_executor 是否针对在带有协程的循环中运行进行了优化?

转载 作者:行者123 更新时间:2023-12-01 15:47:54 27 4
gpt4 key购买 nike

我觉得 run_in_executor() asyncio的方法图书馆属于loop目的。

特别是,如果我选择以“通常”的方式在异步事件循环旁边运行第二个线程,会有什么不同,作者是 import threading , t = threading.Thread(target=...) , t.start() ?

也许答案是使用 asyncio如果循环知道其他线程,则可以在运行时进行低级优化?

最佳答案

您始终可以手动启动另一个线程,但是您有责任让它工作,例如使用队列。在 Python 3 中 concurrent.futures 提供一个方便的 API 来将任务卸载到一个线程池,它称之为 executor。 submit 方法接受一个函数,将它提供给池中的一个线程来运行它,并立即返回一个句柄,当它准备好时将提供结果(或传播异常)。
run_in_executor 是将这种便利带到 asyncio 中。通常你不应该在 asyncio 中运行阻塞代码——即使是像 time.sleep() 这样简单的代码。被禁止,因为它阻塞了整个事件循环。 run_in_executor允许您打破该规则。例如:

async def sleep_test():
loop = asyncio.get_event_loop()
print('going to sleep')
await loop.run_in_executor(None, time.sleep, 5)
#time.sleep(5)
print('waking up')

async def parallel():
# run two sleep_tests in parallel and wait until both finish
await asyncio.gather(sleep_test(), sleep_test())

asyncio.run(parallel())
运行此代码显示协程的两个实例并行 sleep 。如果我们使用 time.sleep()直接,他们会串联 sleep ,因为 sleep 会阻塞事件循环。
这个例子当然很傻,因为有 asyncio.sleep() 挂起协程而不在线程池中占用插槽,但它显示了基本思想。 run_in_executor 的实际用例包括:
  • 从 asyncio
  • 中运行受 CPU 限制的代码,例如 numpy 计算
  • 调用尚未移植到 asyncio 的遗留代码
  • 在非阻塞 API 根本不可用的情况下阻塞调用(数据库驱动程序、文件系统访问)
  • 关于python-asyncio - run_in_executor 是否针对在带有协程的循环中运行进行了优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55027940/

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