簡體   English   中英

Python:如果不使用 asyncio.gather(),為什么要使用 AsyncIO?

[英]Python: why use AsyncIO if not with asyncio.gather()?

我最近開始研究 Python 中的異步編程。 假設我們想異步運行一個函數,下面是一個例子:

async def print_i_async(no):
    print("Async: Preparing print of " + str(no))
    await asyncio.sleep(1)
    print(str(no))

async def main_async(no):
    await asyncio.gather(*(print_i_async(i) for i in range(no)))

asyncio.run(main_async(no))

這將按預期異步工作。 然而,我不清楚,如果不使用asyncio.gather() ,我們為什么要使用異步函數。 例如:

def print_i_serial(no):
    print("Serial: Preparing print of " + str(no))
    time.sleep(1)
    print(str(no))

for i in range(5):
    print_i_serial(i)

for i in range(5):
    asyncio.run(print_i_async(i))

這兩個函數產生相同的結果。 我錯過了什么嗎? 如果我們不使用asyncio.gather() ,我們是否有任何理由使用async def ,因為這是我們實際獲得異步結果的方式?

除了gather之外,還有很多使用asyncio原因。

您真正要問的是:除了gather之外,還有更多方法可以創建並發執行嗎?

答案是肯定的。

是的, gather是使用asyncio創建並發性的最簡單、最直接的示例asyncio ,但它不僅限於gather gather所做的是創建一堆等待對象(如果需要,例如協程被包裝在一個任務中)以等待並在所有期貨准備好后返回結果(以及一堆其他東西,例如傳播取消)。

讓我們再看兩個實現並發的方法的例子:

  1. as_completed - 與gather類似,您發送一堆可等待對象,但不是等待所有等待對象都准備好,此方法會在它們准備好、無序時返回給您。
  2. 另一個例子是自己創建任務,例如使用event_loop.create_task() 這將允許您創建一個將在事件循環上運行的任務,您可以稍后await 同時(直到您await任務)您可以繼續運行其他代碼,並基本上實現並發(注意任務不會立即運行,但只有當您將控制權交還給事件循環並處理任務時)。

實現並發的方法還有很多。 您可以從這些示例開始(第二個示例實際上是您可以用來創建許多不同的並發執行“拓撲”的通用方法)。

您可以先閱讀https://docs.python.org/3/library/asyncio-task.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM