欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python?異之如何同時運行多個協(xié)程詳解

 更新時間:2023年03月22日 14:12:06   作者:冷凍工廠  
這篇文章主要為大家介紹了Python?異之如何同時運行多個協(xié)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

asyncio 的一個好處是我們可以同時運行許多協(xié)程。這些協(xié)同程序可以在一個組中創(chuàng)建并存儲,然后同時一起執(zhí)行。這可以使用 asyncio.gather() 函數(shù)來實現(xiàn)。

讓我們仔細看看。

1. 什么是 Asyncio gather()

asyncio.gather() 模塊函數(shù)允許調用者將多個可等待對象組合在一起。分組后,可等待對象可以并發(fā)執(zhí)行、等待和取消。

它是一個有用的實用函數(shù),可用于分組和執(zhí)行多個協(xié)程或多個任務。

...
# run a collection of awaitables
results = await asyncio.gather(coro1(), asyncio.create_task(coro2()))

在我們可能預先創(chuàng)建許多任務或協(xié)程然后希望一次執(zhí)行它們并等待它們全部完成后再繼續(xù)的情況下,我們可以使用 asyncio.gather() 函數(shù)。

這是一種可能的情況,其中需要許多類似任務的結果,例如具有不同數(shù)據(jù)的相同任務或協(xié)程。

可等待對象可以并發(fā)執(zhí)行,返回結果,并且主程序可以通過使用它所依賴的結果來恢復。

gather() 函數(shù)比簡單地等待任務完成更強大。它允許將一組可等待對象視為單個可等待對象。

  • 通過 await 表達式執(zhí)行并等待組中的所有可等待對象完成。
  • 從所有分組的等待對象中獲取結果,稍后通過 result() 方法檢索。
  • 要通過 cancel() 方法取消的一組等待對象。
  • 通過 done() 方法檢查組中的所有可等待對象是否已完成。
  • 僅當組中的所有任務完成時才執(zhí)行回調函數(shù)。

2. 如何使用 Asyncio gather()

在本節(jié)中,我們將仔細研究如何使用 asyncio.gather() 函數(shù)。

asyncio.gather() 函數(shù)將一個或多個可等待對象作為參數(shù)?;叵胍幌?,可等待對象可能是協(xié)程、Future 或 Task。

因此,我們可以調用 gather() 函數(shù):

  • 多項任務
  • 多個協(xié)程
  • 任務和協(xié)程的混合
...
# execute multiple coroutines
asyncio.gather(coro1(), coro2())

如果 Task 對象被提供給 gather(),它們將已經(jīng)在運行,因為 Tasks 被安排為創(chuàng)建的一部分。asyncio.gather() 函數(shù)將可等待對象作為位置參數(shù)。

我們不能創(chuàng)建可等待對象的列表或集合并將其提供給收集,因為這會導致錯誤。

...
# cannot provide a list of awaitables directly
asyncio.gather([coro1(), coro2()])

如果首先使用星號運算符 (*) 將其解壓縮到單獨的表達式中,則可以提供等待列表。

...
# gather with an unpacked list of awaitables
asyncio.gather(*[coro1(), coro2()])

如果協(xié)程提供給 gather(),它們會自動包裝在 Task 對象中。gather() 函數(shù)不會阻塞。

相反,它返回一個代表可等待對象組的 asyncio.Future 對象。

...
# get a future that represents multiple awaitables
group = asyncio.gather(coro1(), coro2())

一旦創(chuàng)建了 Future 對象,它就會在事件循環(huán)中自動調度。awaitable 代表組,組中的所有 awaitable 都會盡快執(zhí)行。這意味著如果調用者什么都不做,那么預定的可等待對象組將運行(假設調用者掛起)。

這也意味著您不必等待從 gather() 返回的 Future。

...
# get a future that represents multiple awaitables
group = asyncio.gather(coro1(), coro2())
# suspend and wait a while, the group may be executing..
await asyncio.sleep(10)

可以等待返回的 Future 對象,它將等待組中的所有可等待對象完成。

...
# run the group of awaitables
await group

等待從 gather() 返回的 Future 將返回可等待對象的返回值列表。

如果可等待對象沒有返回值,則此列表將包含默認的“無”返回值。

...
# run the group of awaitables and get return values
results = await group

這通常在一行中執(zhí)行。

...
# run tasks and get results on one line
results = await asyncio.gather(coro1(), coro2())

3. 列表中多個協(xié)程的 gather() 示例

預先創(chuàng)建多個協(xié)程然后再收集它們是很常見的。這允許程序準備要并發(fā)執(zhí)行的任務,然后立即觸發(fā)它們的并發(fā)執(zhí)行并等待它們完成。

我們可以手動或使用列表理解將許多協(xié)程收集到一個列表中。

...
# create many coroutines
coros = [task_coro(i) for i in range(10)]

然后我們可以用列表中的所有協(xié)程調用 gather()。協(xié)程列表不能直接提供給 gather() 函數(shù),因為這會導致錯誤。相反,gather() 函數(shù)要求將每個可等待對象作為單獨的位置參數(shù)提供。

這可以通過將列表展開為單獨的表達式并將它們傳遞給 gather() 函數(shù)來實現(xiàn)。星號運算符 (*) 將為我們執(zhí)行此操作。

...
# run the tasks
await asyncio.gather(*coros)

將它們結合在一起,下面列出了使用 gather() 運行預先準備好的協(xié)程列表的完整示例。

# SuperFastPython.com
# example of gather for many coroutines in a list
import asyncio
# coroutine used for a task
async def task_coro(value):
    # report a message
    print(f'>task {value} executing')
    # sleep for a moment
    await asyncio.sleep(1)
# coroutine used for the entry point
async def main():
    # report a message
    print('main starting')
    # create many coroutines
    coros = [task_coro(i) for i in range(10)]
    # run the tasks
    await asyncio.gather(*coros)
    # report a message
    print('main done')
# start the asyncio program
asyncio.run(main())

運行該示例會執(zhí)行 main() 協(xié)程作為程序的入口點。main() 協(xié)程然后使用列表理解創(chuàng)建一個包含 10 個協(xié)程對象的列表。然后將此列表提供給 gather() 函數(shù),并使用星號運算符將其解壓縮為 10 個單獨的表達式。

然后 main() 協(xié)程等待從調用 gather() 返回的 Future 對象,暫停并等待所有調度的協(xié)程完成它們的執(zhí)行。協(xié)程會盡快運行,報告它們獨特的消息并在終止前休眠。

只有在組中的所有協(xié)程都完成后,main() 協(xié)程才會恢復并報告其最終消息。這突出了我們如何準備協(xié)程集合并將它們作為單獨的表達式提供給 gather() 函數(shù)。

main starting
>task 0 executing
>task 1 executing
>task 2 executing
>task 3 executing
>task 4 executing
>task 5 executing
>task 6 executing
>task 7 executing
>task 8 executing
>task 9 executing
main done

以上就是Python 異之如何同時運行多個協(xié)程詳解的詳細內容,更多關于Python 異步同時運行多個協(xié)程的資料請關注腳本之家其它相關文章!

相關文章

最新評論