Created
February 25, 2019 16:54
-
-
Save johanste/b273c8663922c0ef11d2328b847dcf6b to your computer and use it in GitHub Desktop.
Wrapping async in sync
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 Client: | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.loop.call_soon_threadsafe(self.loop.stop) | |
self.loop.call_soon_threadsafe(self.loop.close) | |
def __init__(self): | |
self.loop = asyncio.new_event_loop() | |
self._thread = threading.Thread( | |
target=Client._initialize_loop, args=(self.loop,) | |
) | |
self._thread.daemon = True | |
self._thread.start() | |
@staticmethod | |
def _initialize_loop(loop): | |
asyncio.set_event_loop(loop) | |
loop.run_forever() | |
def run_exec(self, func, *args, **kwargs): | |
future = asyncio.run_coroutine_threadsafe(func(*args, **kwargs), self.loop) | |
return future.result() | |
async def do_more_async_stuff(self, value): | |
print(f"Doing more async stuff {value}") | |
await asyncio.sleep(value) | |
print(f"Done doing more async stuff {value}") | |
async def do_async_stuff(self, value): | |
print(f"Doing async stuff") | |
await asyncio.gather( | |
self.do_more_async_stuff(1), | |
self.do_more_async_stuff(2), | |
self.do_more_async_stuff(3), | |
) | |
print(f"Done async stuff") | |
return value | |
def do_async_stuff_sync(self, value): | |
return Client.run_exec(self, self.do_async_stuff, value) | |
with Client() as client: | |
result = client.do_async_stuff_sync(1) | |
print(result) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment