sh2/d2ypp2/src/async_thread_loop.py
2026-06-02 03:19:23 -05:00

19 lines
563 B
Python

"""Per-thread asyncio event loop reuse (avoids asyncio.run() overhead in recorder threads)."""
from __future__ import annotations
import asyncio
import threading
from typing import Any, Coroutine, TypeVar
_T = TypeVar("_T")
_tls = threading.local()
def run_async_coro(coro: Coroutine[Any, Any, _T]) -> _T:
loop: asyncio.AbstractEventLoop | None = getattr(_tls, "loop", None)
if loop is None or loop.is_closed():
loop = asyncio.new_event_loop()
_tls.loop = loop
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)