小編給大家分享一下關于python中asyncio的用法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
python之asyncio三種應用方法:
1、直接使用asyncio.run方法
import asyncio
#第一種
async def aa():
print("我們的門又壞了")
await asyncio.sleep(2)
print("怎么辦啊")
asyncio.run(aa())2、同步的效果,用await調用函數
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())3、創建任務(asyncio.create_task),并發運行任務(await asyncio.gather)
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()看完了這篇文章,相信你對關于python中asyncio的用法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。