Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Created January 7, 2022 09:46
Show Gist options
  • Select an option

  • Save narenaryan/0515dd30bb87ba62dcda8319d636030e to your computer and use it in GitHub Desktop.

Select an option

Save narenaryan/0515dd30bb87ba62dcda8319d636030e to your computer and use it in GitHub Desktop.
import asyncio
# A co-routine
async def add(x: int, y: int):
return x + y
# Create a function to schedule co-routines on the event loop
# then print results
async def get_results():
inputs = [(2,3), (4,5), (5,5), (7,2)]
# Create a co-routine list
cors = [add(x,y) for x,y in inputs]
# Prints results of co-routines as they are ready
# Beware of Non-deterministic ouput. The order can change based on
# which co-routine finishes first
for cor in asyncio.as_completed(cors):
print(await cor)
asyncio.run(get_results())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment