The gather() function of asyncio module in Python

Overview:

  • The gather() function starts and runs multiple awaitables concurrently, grouping them as a Future.

  • Awaiting on the returned Future object runs the awaitables to completion and returns the results.

Example:

# An example Python program that 
# runs multiple coroutines concurrently
# using asyncio.gather()
import asyncio

# A coroutine that generates odd numbers
async def oddgen(limit):
    cur = 1
    print("From oddgen:%d"%cur)
    
    while cur < limit:
        cur = cur + 2
        print("From oddgen:%d"%cur)
        await asyncio.sleep(0)
    return cur

# A coroutine that generates even numbers
async def evengen(limit):
    cur = 0
    print("From evengen:%d"%cur)
    
    while cur < limit:
        cur = cur + 2
        print("From evengen:%d"%cur)
        await asyncio.sleep(0)
    return cur

# Coroutine that is bootstrapped by 
# the asyncio event loop 
async def main():
    res = await asyncio.gather(oddgen(5), evengen(10))
    print("Results from asyncio.gather():%s"%res)

el = asyncio.new_event_loop()
asyncio.set_event_loop(el)
asyncio.run(main())

Output:

From oddgen:1

From oddgen:3

From evengen:0

From evengen:2

From oddgen:5

From evengen:4

From evengen:6

From evengen:8

From evengen:10

Results from asyncio.gather():[5, 10]

 


Copyright 2024 © pythontic.com