Skip to content

Instantly share code, notes, and snippets.

@johanste
Created February 25, 2019 16:54
Show Gist options
  • Save johanste/b273c8663922c0ef11d2328b847dcf6b to your computer and use it in GitHub Desktop.
Save johanste/b273c8663922c0ef11d2328b847dcf6b to your computer and use it in GitHub Desktop.
Wrapping async in sync
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