Created
December 11, 2019 12:43
-
-
Save gidj/d21c4a14b9916c50a3dc6a0be6641f2b to your computer and use it in GitHub Desktop.
Asyncio iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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