asyncio模块中的Future和Task
task是可以理解为单个coroutine,经过ensure_future方法处理而形成,而众多task所组成的集合经过asyncio.gather处理而形成一个future。
再不精确的粗略的说,future就是存放着众多task或future的容器。
而task又是future的子类,所以不管是task还是future还是coreture都可以看成是一个广义的携程,future无非是一个内部包含众多携程的大携程而已,await后面,task,coroture,future都可以接。
ensure_future 可以将 coroutine 封装成 Task。
asyncio.ensure_future(coro_or_future, *, loop=None)
Schedule the execution of a coroutine object: wrap it in a future. Return a Task object.If the argument is a Future, it is returned directly.
import asyncio async def hello(name): await asyncio.sleep(2) print('Hello, ', name) coroutine = hello("World") a = asyncio.ensure_future(coroutine)# print (a.__class__)#Task b=asyncio.Future()#标准future print (b.__class__)#Future print (issubclass(a.__class__,b.__class__))#true,Task类是Future类的子类 #首先a是一个Task,又因为Task类是Futrue类的子类,所以,我们也可以说,a是一个Future #下面验证If the argument is a Future, it is returned directly. c=asyncio.ensure_future(b)# print (c is b)#true d=asyncio.ensure_future(a)# print (d is a)#True
----------------------------------------分割线----------------------------------------
asyncio.gather 将一些 Future 和 coroutine 封装成一个 Future。
asyncio.wait方法则返回一个 coroutine。
run_until_complete 既可以接收 Future 对象,也可以是 coroutine 对象,如果是coroutine,则先把他转化为future
BaseEventLoop.run_until_complete(future)
Run until the Future is done.
If the argument is a coroutine object, it is wrapped by ensure_future().
Return the Future's result, or raise its exception.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现