Skip to content

Allow re-entry into the event loop using tokens #256

Closed

Description

@agronholm

Trio allows using trio.from_thread.run and trio.from_thread.run_sync to be called from unrelated threads as long as a token (from trio.low_level.current.token) is provided.

On asyncio this token could be the event loop object itself, or another object that wraps it.

This change would likely allow us to remove the __new__() hack from BlockingPortal.

Activity

  1. added this to the 3.1 milestone on Apr 10, 2021
  2. removed this from the 3.x milestone on Oct 2, 2022
  3. arthur-tacca commented on Nov 15, 2022

    @arthur-tacca

    For applications where all that is needed is fire and forget, the implementations could be trivial, even assuming today's current_token() implementation (returns the TrioToken in Trio, and the event loop in asyncio).

    In trio:

    def run_sync_soon_from_thread(token, sync_fn, *args):
        assert isinstance(token, trio.lowlevel.TrioToken)
        token.run_sync_soon(sync_fn, *args)

    In asyncio:

    def run_sync_soon_from_thread(token, sync_fn, *args):
        assert isinstance(token, asyncio.AbstractEventLoop)
        token.call_soon_threadsafe(sync_fn, *args)

    The only slight niggle is that if the loop has exited then asyncio raises RuntimeError whereas Trio raises trio.RunFinishedError, but the latter derives from RuntimeError so that could be the documented exception type.

    More complex applications need to wait until the sync_fn has finished or allow async callbacks, and I recognise that's trickier.

  4. added a commit that references this issue on Sep 9, 2025
    ebcf023
  5. added a commit that references this issue on Sep 11, 2025
    920a072
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions