Skip to content

Commit

Permalink
BUG: Fix crash when exiting the daemon thread (#117)
Browse files Browse the repository at this point in the history
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
codingl2k1 and mergify[bot] authored Dec 1, 2024
1 parent 0f28fe7 commit 4126e1e
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions python/xoscar/backends/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,16 +208,52 @@ def cancel_tasks(self):
_ = [task.cancel() for task in self._clients.values()]


def _cancel_all_tasks(loop):
to_cancel = asyncio.all_tasks(loop)
if not to_cancel:
return

for task in to_cancel:
task.cancel()

loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))

for task in to_cancel:
if task.cancelled():
continue
if task.exception() is not None:
loop.call_exception_handler(
{
"message": "unhandled exception during asyncio.run() shutdown",
"exception": task.exception(),
"task": task,
}
)


def _safe_run_forever(loop):
loop.run_forever()
_cancel_all_tasks(loop)


def _safe_exit_thread(loop, thread):
# To avoid _enter_buffered_busy: could not acquire lock
loop.call_soon_threadsafe(loop.stop)
thread.join()


class ActorCaller:
__slots__ = "_thread_local"

class _RefHolder:
pass

_close_loop = asyncio.new_event_loop()
_close_thread = threading.Thread(target=_close_loop.run_forever, daemon=True)
_close_thread = threading.Thread(
target=_safe_run_forever, args=(_close_loop,), daemon=True
)
_close_thread.start()
atexit.register(_close_loop.call_soon_threadsafe, _close_loop.stop)
atexit.register(_safe_exit_thread, _close_loop, _close_thread)

def __init__(self):
self._thread_local = threading.local()
Expand Down

0 comments on commit 4126e1e

Please sign in to comment.