asyncio異步編程之Task對(duì)象詳解
更新時(shí)間:2022年03月11日 15:45:46 作者:一起學(xué)python吧
這篇文章主要為大家詳細(xì)介紹了asyncio異步編程之Task對(duì)象,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
1.Task對(duì)象的作用
可以將多個(gè)任務(wù)添加到事件循環(huán)當(dāng)中,達(dá)到多任務(wù)并發(fā)的效果
2.如何創(chuàng)建task對(duì)象
asyncio.create_task(協(xié)程對(duì)象)
注意:create_task
只有在python3.7及以后的版本中才可以使用,就像asyncio.run()
一樣,
在3.7以前可以使用asyncio.ensure_future()
方式創(chuàng)建task對(duì)象
3.示例一(目前不推薦這種寫法)
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()) """ 在創(chuàng)建task的時(shí)候,就將創(chuàng)建好的task添加到了時(shí)間循環(huán)當(dāng)中,所以說必須得有時(shí)間循環(huán),才可以創(chuàng)建task,否則會(huì)報(bào)錯(cuò) """
4.示例2
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") # 執(zhí)行成功后結(jié)果在done中, wait中可以加第二個(gè)參數(shù)timeout,如果在超時(shí)時(shí)間內(nèi)沒有完成,那么pending就是未執(zhí)行完的東西 done, pending = await asyncio.wait(tasks, timeout=1) print(done) #print(pending) # python3.7以前的寫法 loop = asyncio.get_event_loop() loop.run_until_complete(main1())
5.示例3(算是以上示例2的簡(jiǎn)化版)
""" 方式二的簡(jiǎn)化版,就是tasks中不直接添加task,而是先將協(xié)程對(duì)象加入到list中,在最后運(yùn)行中添加 """ 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)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
PyCharm代碼整體縮進(jìn),反向縮進(jìn)的方法
今天小編就為大家分享一篇PyCharm代碼整體縮進(jìn),反向縮進(jìn)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06matplotlib設(shè)置坐標(biāo)軸標(biāo)簽和間距的實(shí)現(xiàn)
本文主要介紹了matplotlib設(shè)置坐標(biāo)軸標(biāo)簽和間距的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10