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.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM