Skip to content

Instantly share code, notes, and snippets.

@nguyendv
Last active April 4, 2019 23:09
Show Gist options
  • Save nguyendv/d58fb0f75f8129ad6d33c01affcf261d to your computer and use it in GitHub Desktop.
Save nguyendv/d58fb0f75f8129ad6d33c01affcf261d to your computer and use it in GitHub Desktop.
Run Python synchronous functions in an asynchronous manner
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