Skip to content

Instantly share code, notes, and snippets.

@gidj
Created December 11, 2019 12:43
Show Gist options
  • Save gidj/d21c4a14b9916c50a3dc6a0be6641f2b to your computer and use it in GitHub Desktop.
Save gidj/d21c4a14b9916c50a3dc6a0be6641f2b to your computer and use it in GitHub Desktop.
Asyncio iterator
import asyncio
import random
ten = tuple(range(10))
async def ran_sleep(param):
value = random.choice(ten)
await asyncio.sleep(value)
print("{0} Sleep value:{1}".format(param, value))
return (param, value)
async def main():
results = await asyncio.gather(*map(ran_sleep, range(20)))
print(results)
async def main1():
results = await asyncio.gather(*[ran_sleep(num) for num in range(20)])
print(results)
async def main2():
results = [await ran_sleep(num) for num in range(20)]
print(results)
asyncio.run(main()) # Concurrent
asyncio.run(main1()) # Concurrent
asyncio.run(main2()) # NOT Concurrent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment