Created
February 14, 2021 15:49
-
-
Save kumaraditya303/861c0675d7e952e4123d92e10b501ed9 to your computer and use it in GitHub Desktop.
Run Async function as blocking function without running it in main thread
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 | |
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