简体   繁体   English

asyncio 事件循环是否只运行任务?

[英]Does the asyncio event loop only run tasks?

I'm in the early stages of learning about the asyncio library.我正处于学习 asyncio 库的早期阶段。 I'm starting off with coroutines and tasks, and reading through the hello world examples in the docs .我从协程和任务开始,并通读 文档中的hello world示例。

Based on the section about coroutines, it seems there are two main ways of running a coroutine object:根据有关协程的部分,似乎有两种主要的方式来运行协程 object:

  • Using await on a coroutine在协程上使用await
  • Running coroutines as asyncio Tasks将协程作为 asyncio 任务运行

According to the Task docs:根据任务文档:

Tasks are used to run coroutines in event loops.任务用于在事件循环中运行协程。

To be clear, does this imply the event loop doesn't run coroutine objects unless they are wrapped into a task?明确地说,这是否意味着事件循环不会运行协程对象,除非它们被包装到任务中? In this situation, are these coroutine objects just run synchronously without any interaction with the event loop?在这种情况下,这些协程对象是否只是同步运行而没有与事件循环进行任何交互?

To be clear, does this [that tasks are used to run coroutines] imply the event loop doesn't run coroutine objects unless they are wrapped into a task?明确地说,这 [任务用于运行协程] 是否意味着事件循环不运行协程对象,除非它们被包装到任务中?

It means that tasks are the entry point into the coroutine world.这意味着任务是协程世界的入口点。 Each coroutine can be traced to being awaited by an outer coroutine, all the way to a coroutine that is driven by a task.每个协程都可以追溯到被外部协程等待,一直到由任务驱动的协程。

Take this example code:拿这个例子代码:

async def inner():
    await asyncio.sleep(1)

async def outer():
    await inner()
    await inner()

async def main():
    await outer()

asyncio.run(main())

asyncio.run implicitly creates one task to drive the main coroutine to completion. asyncio.run隐式创建一个任务来驱动main协程完成。 The task only "sees" the coroutine object created by invoking main() and is unconcerned with the coroutine main awaits.该任务仅“看到”通过调用main()创建的协程 object,而不关心协程main等待。 From the point of view of the task, main will suspend twice, once for each sleep .从任务的角度来看, main会挂起两次,每次sleep一次。 Prior to suspending, the sleep coroutine will arrange with the event loop for the task to be resumed.在挂起之前, sleep协程将与事件循环一起安排要恢复的任务。

In this situation, are these coroutine objects just run synchronously without any interaction with the event loop?在这种情况下,这些协程对象是否只是同步运行而没有与事件循环进行任何交互?

All coroutines must interact with the event loop because they must be able to suspend .所有协程都必须与事件循环交互,因为它们必须能够挂起 If they are awaited by another coroutine, they cause the awaiting coroutine to suspend.如果它们被另一个协程等待,它们会导致等待的协程挂起。 This propagates up to the top-level coroutine which is run by a task, and that causes the task to suspend.这会传播到由任务运行的顶级协程,并导致任务挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM