asyncio.create_task()有什么作用? [英] What does asyncio.create_task() do?

查看:208
本文介绍了asyncio.create_task()有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

asyncio.create_task()有什么作用?我看了看文档,似乎看不懂.一些让我感到困惑的代码是这样的:

What does asyncio.create_task() do? I have looked at the docs and can't seem to understand it. A bit of code that confuses me is this:

import asyncio

async def counter_loop(x, n):
    for i in range(1, n + 1):
        print(f"Counter {x}: {i}")
        await asyncio.sleep(0.5)
    return f"Finished {x} in {n}"

async def main():
    slow_task = asyncio.create_task(counter_loop("Slow", 4))
    fast_coro = counter_loop("Fast", 2)

    print("Awaiting Fast")
    fast_val = await fast_coro
    print("Finished Fast")

    print("Awaiting Slow")
    slow_val = await slow_task
    print("Finished Slow")

    print(f"{fast_val}, {slow_val}")

asyncio.run(main())

这将提供以下输出:

001 | Awaiting Fast
002 | Counter Fast: 1
003 | Counter Slow: 1
004 | Counter Fast: 2
005 | Counter Slow: 2
006 | Finished Fast
007 | Awaiting Slow
008 | Counter Slow: 3
009 | Counter Slow: 4
010 | Finished Slow
011 | Finished Fast in 2, Finished Slow in 4

我不太了解这是如何工作的.

I don't understand quite how this is working.

  1. slow_task 不能运行,直到完成 fast_coro ,因为它从未在 asyncio.gather 中使用方法?
  2. 我们为什么必须等待slow_task ?
  3. 为什么协程似乎开始后为什么要打印 Awaiting Slow ?
  4. 什么是任务?我知道 gather 所做的是安排一个任务.而 create_task 应该创建一个任务.
  1. Shouldn't the slow_task not be able to run until the completion of the fast_coro because it was never used in an asyncio.gather method?
  2. Why do we have to await slow_task?
  3. Why is Awaiting Slow printed after the coroutine appears to have started?
  4. What really is a task? I know that what gather is doing is scheduling a task. And create_task supposedly creates a task.

一个深入的答案将不胜感激.谢谢!

An in-depth answer would be greatly appreciated. Thanks!

也许值得一提的是,我对期货知之甚少.

It also might be worth mentioning that I know very little about Futures.

推荐答案

asyncio.create_task()做什么?

它提交协程以在后台"运行,即与当前任务和所有其他任务并行.它返回称为任务"的等待句柄.您还可以使用它取消协程的执行.

It submits the coroutine to run "in the background", i.e. in parallel with the current task and all other tasks. It returns an awaitable handle called a "task" which you can also use to cancel the execution of the coroutine.

它是asyncio的核心原语之一,相当于启动线程的asyncio.(以类似的方式,用 await 等待任务等同于加入线程.)

It's one of the central primitives of asyncio, the asyncio equivalent of starting a thread. (In the same analogy, awaiting the task with await is the equivalent of joining a thread.)

slow_task 直到 fast_coro

否,因为您明确使用 create_task 在后台启动 slow_task .你写过类似的东西吗?

No, because you explicitly used create_task to start slow_task in the background. Had you written something like:

    slow_coro = counter_loop("Slow", 4)
    fast_coro = counter_loop("Fast", 2)
    fast_val = await fast_coro

...实际上 slow_coro 无法运行,因为尚无人将其提交到事件循环.但是 create_task 确实做到了这一点:将其提交到事件循环中以与其他任务同时执行,切换点是任何 await .

...indeed slow_coro would not run because no one would have yet submitted it to the event loop. But create_task does exactly that: submit it to the event loop for execution concurrently with other tasks, the point of switching being any await.

因为它从未在 asyncio.gather 方法中使用过?

asyncio.gather 并不是在asyncio中实现并发的唯一方法.它只是一个实用程序函数,它使得等待许多协程完成并同时将它们提交到事件循环变得更加容易. create_task 仅执行提交,它可能应该被称为 start_coroutine 或类似的名称.

asyncio.gather is not the only way to achieve concurrency in asyncio. It's just a utility function that makes it easier to wait for a number of coroutines to all complete, and submit them to the event loop at the same time. create_task does just the submitting, it should have probably been called start_coroutine or something like that.

我们为什么要等待 slow_task ?

我们没有,它只是用来等待两个协程顺利完成.该代码还可能已经等待 asyncio.sleep()或类似的东西.立即从 main()(以及事件循环)返回并且仍然有一些待处理的任务也可以正常工作,但是它会打印一条警告消息,指出可能的错误.在停止事件循环之前等待(或取消)任务比较干净.

We don't have to, it just serves to wait for both coroutines to finish cleanly. The code could have also awaited asyncio.sleep() or something like that. Returning from main() (and the event loop) immediately with some tasks still pending would have worked as well, but it would have printed a warning message indicating a possible bug. Awaiting (or canceling) the task before stopping the event loop is just cleaner.

真正的任务是什么?

What really is a task?

这是一个异步构造,用于在具体事件循环中跟踪协程的执行.当您调用 create_task 时,您将提交一个协程以执行并收到一个句柄.您可以在实际需要结果时等待该句柄,或者如果您不在乎结果,就永远不能等待它.该句柄是 task ,它继承自 Future ,这使其可以等待,并提供了基于较低级别的基于回调的接口,例如 add_done_callback .

It's an asyncio construct that tracks execution of a coroutine in a concrete event loop. When you call create_task, you submit a coroutine for execution and receive back a handle. You can await this handle when you actually need the result, or you can never await it, if you don't care about the result. This handle is the task, and it inherits from Future, which makes it awaitable and also provides the lower-level callback-based interface, such as add_done_callback.

这篇关于asyncio.create_task()有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆