Skip to content

Instantly share code, notes, and snippets.

@kumaraditya303
Created February 14, 2021 15:49
Show Gist options
  • Save kumaraditya303/861c0675d7e952e4123d92e10b501ed9 to your computer and use it in GitHub Desktop.
Save kumaraditya303/861c0675d7e952e4123d92e10b501ed9 to your computer and use it in GitHub Desktop.
Run Async function as blocking function without running it in main thread
import asyncio
from threading import Thread, enumerate
def async_to_sync() -> asyncio.AbstractEventLoop:
loop = asyncio.new_event_loop()
Thread(target=loop.run_forever).start()
return loop
async def main():
await asyncio.sleep(10)
return "Hello World from async loop running in a background thread"
loop = async_to_sync()
result = asyncio.run_coroutine_threadsafe(main(), loop)
print(asyncio.get_event_loop().is_running())
print(loop.is_running())
print(result.result())
print(enumerate())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment