python之asyncio三種應用方法


1、直接使用asyncio.run方法
2、同步的效果,用await調用函數
3、創建任務(asyncio.create_task),並發運行任務(await asyncio.gather)



import asyncio #第一種 async def aa(): print("我們的門又壞了") await asyncio.sleep(2) print("怎么辦啊") asyncio.run(aa()) # 第二種 同步的效果 async def fun1(): print("增強體育鍛煉,提高免疫力") await asyncio.sleep(3) print("才能保證身體健康,諸事順利") async def fun2(): await asyncio.sleep(5) print("這個周末天氣不錯") await asyncio.sleep(8) print("可是你就是不想出去") async def min(): await fun1() await fun2() if __name__ == "__main__": asyncio.run(min()) # # 第三種並發 # 吃魚丸 arr = [] async def produce(): for i in range(100): await asyncio.sleep(1) arr.append(i) print("小明放了一個魚丸,現在鍋里還有%s個魚丸"%len(arr)) async def consumer(): while True: await asyncio.sleep(2) #很關鍵 if len(arr)>=10: #各一個判斷條件 arr.pop() print("mony吃了一個魚丸,現在鍋里還有%s個魚丸"%len(arr)) async def main(): t1 = asyncio.create_task(produce()) #創建任務 t2 = asyncio.create_task(consumer()) await asyncio.gather(t1,t2) #並發運行任務 asyncio.run(main()) #調用函數main()

  


免責聲明!

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



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