小編給大家分享一下asyncio異步編程中Task對象是什么,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
可以將多個任務添加到事件循環當中,達到多任務并發的效果
asyncio.create_task(協程對象)
注意:create_task
只有在python3.7及以后的版本中才可以使用,就像asyncio.run()
一樣,
在3.7以前可以使用asyncio.ensure_future()
方式創建task對象
async def func(): print(1) await asyncio.sleep(2) print(2) return "test" async def main(): print("main start") # python 3.7及以上版本的寫法 # task1 = asyncio.create_task(func()) # task2 = asyncio.create_task(func()) # python3.7以前的寫法 task1 = asyncio.ensure_future(func()) task2 = asyncio.ensure_future(func()) print("main end") ret1 = await task1 ret2 = await task2 print(ret1, ret2) # python3.7以后的寫法 # asyncio.run(main()) # python3.7以前的寫法 loop = asyncio.get_event_loop() loop.run_until_complete(main()) """ 在創建task的時候,就將創建好的task添加到了時間循環當中,所以說必須得有時間循環,才可以創建task,否則會報錯 """
async def func1(): print(1111) await asyncio.sleep(2) print(2222) return "test" async def main1(): print("main start") tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func1()) ] print("main end") # 執行成功后結果在done中, wait中可以加第二個參數timeout,如果在超時時間內沒有完成,那么pending就是未執行完的東西 done, pending = await asyncio.wait(tasks, timeout=1) print(done) #print(pending) # python3.7以前的寫法 loop = asyncio.get_event_loop() loop.run_until_complete(main1())
""" 方式二的簡化版,就是tasks中不直接添加task,而是先將協程對象加入到list中,在最后運行中添加 """ async def func2(): print(1111) await asyncio.sleep(2) print(2222) return "test" tasks = [ func2(), func2() ] # python3.7以前的寫法 loop = asyncio.get_event_loop() done, pending = loop.run_until_complete(asyncio.wait(tasks)) print(done) print(pending)
以上是“asyncio異步編程中Task對象是什么”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。