Created
July 4, 2018 09:24
-
-
Save johnssuh/d18c593fe4f8c0cdbab5ff53a6778e89 to your computer and use it in GitHub Desktop.
Some cool stuff with asyncio
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 | |
| class DummyAPI: | |
| async def get(self, number): | |
| print(f"GET {number} executed") | |
| await asyncio.sleep(number) | |
| return number, "a" | |
| async def context_switched_get(self): | |
| dispatch_list = [] | |
| for i in range(1,6): | |
| dispatch_list.append(asyncio.ensure_future(self.get(i))) | |
| await asyncio.sleep(0) | |
| print("For context switched get, get is executed before this print statement") | |
| done = await asyncio.gather(*dispatch_list, return_exceptions=True) | |
| for e in done: | |
| print(e) | |
| async def gathered_get(self): | |
| dispatch_list = [] | |
| for i in range(1,6): | |
| dispatch_list.append(asyncio.ensure_future(self.get(i))) | |
| print("For regular gathered get, get is executed after this print statement") | |
| done = await asyncio.gather(*dispatch_list, return_exceptions=True) | |
| for e in done: | |
| print(e) | |
| async def main(self): | |
| await self.context_switched_get() | |
| await self.gathered_get() | |
| dummy = DummyAPI() | |
| loop = asyncio.get_event_loop() | |
| loop.run_until_complete(dummy.main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment