使用 yield from 时协程 运行 在哪个事件循环中执行?

In which event loop does a coroutine run when using yield from?

当我在协程 foo 中调用 yield from some_coroutine() 时,some_coroutine 是否安排在与 foo 当前 运行 相同的偶数循环中在?一个例子:

async def foo():
    yield from asyncio.sleep(5)

loop = asyncio.get_event_loop() # this could also be a custom event loop
loop.run_until_completed(foo())

在此示例中,sleep 将安排在哪个事件循环中?我对 loop 不是默认事件循环的情况特别感兴趣。

documentation,在"Things a coroutine can do"下说:

result = await coroutine or result = yield from coroutine – wait for another coroutine to produce a result (or raise an exception, which will be propagated). The coroutine expression must be a call to another coroutine.

我不清楚协程将安排在哪个循环中。

引用 get_event_loop

的文档

Get the event loop for the current context.

default loop的实施(事件循环默认策略):

The default policy defines context as the current thread, and manages an event loop per thread that interacts with asyncio.

  • 一个事件循环在一个线程中运行,并在同一个线程中执行所有回调和任务(docs),

  • asyncio.get_event_loop returns同线程同循环,

  • 如果您没有显式安排 on/interact 与不同线程的循环,它将使用默认 (*) 循环

在你的例子中:

  1. get_event_loop returns 当前线程的事件循环,

  2. foo 被安排在 run_until_completed

  3. 的循环中
  4. 任何进一步的异步调用(awaits/yield 来自)都安排在同一个循环中

更多信息请见 Concurrency and multithreading

(*) 你调用的事件循环default实际上是当前线程的一个循环