掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
python之a(chǎn)syncio三種應(yīng)用方法:

1、直接使用asyncio.run方法
import asyncio
#第一種
async def aa():
print("我們的門又壞了")
await asyncio.sleep(2)
print("怎么辦啊")
asyncio.run(aa())
2、同步的效果,用await調(diào)用函數(shù)
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、創(chuàng)建任務(wù)(asyncio.create_task),并發(fā)運行任務(wù)(await asyncio.gather)
arr = []
async def produce():
for i in range(100):
await asyncio.sleep(1)
arr.append(i)
print("小明放了一個魚丸,現(xiàn)在鍋里還有%s個魚丸"%len(arr))
async def consumer():
while True:
await asyncio.sleep(2) #很關(guān)鍵
if len(arr)>=10: #各一個判斷條件
arr.pop()
print("mony吃了一個魚丸,現(xiàn)在鍋里還有%s個魚丸"%len(arr))
async def main():
t1 = asyncio.create_task(produce()) #創(chuàng)建任務(wù)
t2 = asyncio.create_task(consumer())
await asyncio.gather(t1,t2) #并發(fā)運行任務(wù)asyncio.run(main()) #調(diào)用函數(shù)main() 
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流