Last active
April 4, 2019 23:09
-
-
Save nguyendv/d58fb0f75f8129ad6d33c01affcf261d to your computer and use it in GitHub Desktop.
Run Python synchronous functions in an asynchronous manner
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 time, asyncio | |
def stuff(arg1, arg2): | |
# Doing IO | |
pass | |
async def async_stuff(): | |
loop = asyncio.get_event_loop() # get the default event loop | |
loop.run_in_executor(None, stuff, param1, param2) | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
try: | |
# Use gather to run the coroutines concurrently | |
loop.run_until_complete(asyncio.gather(async_stuff(), async_stuff(), async_stuff())) | |
finally: | |
loop.close() | |
""" For Python 3.7+ | |
if __name__ == '__main__': | |
asyncio.run(asyncio.gather(async_stuff(), async_stuff(), async_stuff())) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment