Skip to content

Add an async interface for calling into an event loop running in another thread #1342

Closed

Description

@davidbrochart

Things to check first

  • I have searched the existing issues and didn't find my feature already requested there

Feature description

AnyIO provides from_thread.run() and from_thread.run_sync() for calling into an event loop from a synchronous thread. However, there does not appear to be a direct way for one event-loop thread to asynchronously call into another event-loop thread.

Use case

My use case has two AnyIO event loops:

  • A server event loop in the main thread.
  • A user-code event loop in a dedicated thread.

From the server loop, I would like to run a coroutine in the user-code loop and asynchronously wait for its result:

# Running in the server event loop
result = await call_in_event_loop(
    target_token,
    coroutine_function,
    *args,
)

The closest workaround I have found is:

result = await anyio.to_thread.run_sync(
    anyio.from_thread.run,
    coroutine_function,
    *args,
    token=target_token,
)

This works, but it introduces an intermediary worker thread whose only purpose is to block in from_thread.run(): source event loop → intermediary worker thread → target event loop.

BlockingPortal provides the required access to the target event loop, but BlockingPortal.call() is synchronous. Calling it directly would block the source event loop, while wrapping it in to_thread.run_sync() has the same intermediary-thread issue.

Would an asynchronous portal or token API make sense? For example:

result = await portal.call_async(coroutine_function, *args)

or:

result = await anyio.lowlevel.run_in_event_loop(
    coroutine_function,
    *args,
    token=target_token,
)

The operation would schedule the callable in the target event loop, suspend the calling task without blocking its thread, and propagate the result or exception back to the calling loop.

Some behavior would need to be defined:

  • Whether cancellation of the caller cancels the target coroutine or only abandons the result.
  • How context variables are propagated.
  • What happens if either event loop exits during the operation.
  • Whether calls between different AnyIO backends, such as asyncio and Trio, are supported.
  • What happens when the token refers to the caller’s own event loop.
  • Whether both coroutine and synchronous callable variants should be provided.

Is there already a supported way to do this without occupying an intermediary worker thread? If not, would such an API fit within AnyIO?

Activity

  1. added
    enhancement
    on Sep 23, 2026
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

    enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions