Created
October 7, 2021 00:55
-
-
Save antibagr/a0617476e2f7ca0623475044aafc8e94 to your computer and use it in GitHub Desktop.
Asyncio with threads explained
This file contains 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 | |
import asyncio | |
import threading | |
async def coro(name: str) -> str: | |
await asyncio.sleep(0.001) | |
print(f'[Coroutine] Called with {name=}') | |
return name | |
def call_coro_from_thread() -> None: | |
print('[Second] I\'m going to call a coroutine in the first thread now!') | |
asyncio.run_coroutine_threadsafe(coro('foo'), loop=loop) | |
print('[Second] Done. Closing second thread.') | |
async def main() -> None: | |
for _ in range(3): | |
print('[First] Event loop is running') | |
await asyncio.sleep(0.1) | |
print('[First] Closing event loop and first thread') | |
loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() | |
threads: list[threading.Thread] = [ | |
threading.Thread(target=loop.run_until_complete, args=(main(),)), | |
threading.Thread(target=call_coro_from_thread), | |
] | |
print('[Main] Hello. I\'m going to launch all threads.') | |
for th in threads: | |
th.start() | |
print('[Main] thread is here and it is still free!') | |
time.sleep(0.3) | |
print('[Main] Closing all threads.') | |
for th in threads: | |
th.join() | |
print('[Main] Goodbye!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You would see: