import asyncio
import threading


class LoopRunner:
    def __init__(self):
        self._loop = asyncio.new_event_loop()
        self._t = threading.Thread(target=self._loop.run_forever, daemon=True)
        self._t.start()

    def run(self, coro):
        fut = asyncio.run_coroutine_threadsafe(coro, self._loop)
        return fut.result()

    def stop(self):
        self._loop.call_soon_threadsafe(self._loop.stop)
        self._t.join(timeout=1.0)
