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.

原文地址:https://www.cnblogs.com/saolv/p/9860284.html