Last active
December 12, 2018 06:27
-
-
Save linw1995/2a1429b67c6daa9f882a42131d283e11 to your computer and use it in GitHub Desktop.
run asyncio event loop in another thread.
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 asyncio | |
import threading | |
class AsyncioBackground(threading.Thread): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.loop = asyncio.new_event_loop() | |
def run(self): | |
self.loop.run_forever() | |
def run_coro_threadsafe(self, coro): | |
finished = threading.Event() | |
fut = asyncio.run_coroutine_threadsafe(coro, loop=self.loop) | |
fut.add_done_callback(lambda _: finished.set()) | |
finished.wait() | |
return fut.result() | |
def stop(self): | |
self.loop.call_soon_threadsafe(self.loop.stop) | |
if __name__ == '__main__': | |
from datetime import datetime | |
t = AsyncioBackground() | |
t.start() | |
async def raise_error(): | |
await asyncio.sleep(1) | |
raise ValueError() | |
print(datetime.now()) | |
try: | |
t.run_coro_threadsafe(raise_error()) | |
print(datetime.now()) | |
finally: | |
t.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment