1. 程式人生 > 其它 >python非同步執行緒,實現協程操作

python非同步執行緒,實現協程操作

  •  單個方法簡單實現非同步 async
    # 引入 asyncio 模組才能執行協程函式
    import asyncio
    #使用 async 關鍵字將函式定義為協程函式
    async def func():
        print("Hello World~~~~")
    
    if __name__=='__main__':
        g = func() # 此時的 func() 是非同步協程函式, 函式執行得到的是一個協程物件
        print("~~~~~~~~~~~~~~~")
        asyncio.run(g)  # 協程模組需要 asyncio 的支援
  • 多個非同步方法實現協程操作
    # 執行非同步函式引入 asyncio
    import asyncio # 時間 import time async def func1(): print("func1") # 當程式出現同步操作的時候,非同步就中斷了 request.get() 也是同步操作 #time.sleep(3) # 非同步操作的程式碼 使用asyncio的非同步sleep 並且使用await關鍵字掛起 await asyncio.sleep(3) print("func1 over!") async def func2(): print("func2") #time.sleep(2) 同func1換用 非同步sleep
    await asyncio.sleep(2) print("func2 over!") if __name__ == '__main__': f1 = func1() f2 = func2() tasks = [f1, f2] t1 = time.time() # 一次性啟動多個協程任務 asyncio.run(asyncio.wait(tasks)) t2 = time.time() print(t2 - t1)