python - 为什么我需要将 python 协程包装到任务中/何时使用任务或协程?

标签 python async-await task python-asyncio

在 python 中,有 3 main types awaitable objects :协程、任务和 future 。
我可以 await 一个协程,也可以 tasks
等待协程

import asyncio

async def nested():
    return 42

async def main():
    print(await nested())  # will print "42".

asyncio.run(main())
等待任务
import asyncio

async def nested():
    return 42

async def main():
    task = asyncio.create_task(nested())
    await task

asyncio.run(main())
首先将协程包装在任务中的值(value)是什么?看起来他们做同样的事情。
我什么时候需要使用任务与协程?

最佳答案

协程只是一个在当前等待的上下文中运行的函数。它可以代表调用者 (调用 await 的人)将执行交给事件循环 。想想一个允许暂停它的线程的函数。您可以从另一个调用一个协程,但它们仍然共享同一个线程。
另一方面,任务会立即将单独的 作业 发布到事件循环。任务本身就是该工作的句柄。您可以 await 一个任务,但它可以在“并行”中自行运行——在单线程上下文中,这意味着该任务可以在其他 josb 产生时运行(例如,等待 I/O)。任务可能在您调用 await 之前完成。
没有任务的示例:

job_1 = sleep(5)
job_2 = sleep(2)

# will sleep for 5 seconds
await job_1

# will sleep for another 2 seconds
await job_2
任务示例:
job_1 = sleep(5)
job_2 = asyncio.create_task(sleep(2))

# will sleep for 5 seconds
await job_1

# by this time, job_2 is complete
# because previous job has yielded at some point, allowing other jobs to run
# thus await takes no time
await job_2

关于python - 为什么我需要将 python 协程包装到任务中/何时使用任务或协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67002349/

相关文章:

python - 如何使用 url 在 Python 中访问 s3 文件?

python - Python 中的属性引用

c# - C# 中是否存在异步正则表达式,它们对我的情况有帮助吗?

c# - 当我使用 ToListAsync 方法时,线程不起作用

android - 错误 :Execution failed for task ':Application:transformClassesWithJarMergingForDebug'

python - 通过 4 个索引同时迭代

Python 2.7 套接字 htons

c# - 不需要并发时使用静态方法中的异步等待模式

ruby-on-rails - Ruby:在没有 Rails 的情况下从 gem 访问 rake 任务

c# - 同时运行任务.NET 4.5