Skip to content

Instantly share code, notes, and snippets.

@lars-tiede
Created March 8, 2016 10:37
Show Gist options
  • Save lars-tiede/956206c8d97cbc3454cb to your computer and use it in GitHub Desktop.
Save lars-tiede/956206c8d97cbc3454cb to your computer and use it in GitHub Desktop.
Safely run a coroutine in another thread's asyncio loop and return the result
import threading
import asyncio
async def run_coro_threadsafe(self, coro, other_loop, our_loop = None):
"""Schedules coro in other_loop, awaits until coro has run and returns
its result.
"""
loop = our_loop or asyncio.get_event_loop()
# schedule coro safely in other_loop, get a concurrent.future back
# NOTE run_coroutine_threadsafe requires Python 3.5.1
fut = asyncio.run_coroutine_threadsafe(coro, other_loop)
# set up a threading.Event that fires when the future is finished
finished = threading.Event()
def fut_finished_cb(_):
finished.set()
fut.add_done_callback(fut_finished_cb)
# wait on that event in an executor, yielding control to our_loop
await loop.run_in_executor(None, finished.wait)
# coro's result is now available in the future object
return fut.result()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment