8

I can easily reproduce this issue with this example:

from threading import Thread
import asyncio

def func():
    asyncio.get_event_loop()

Thread(target=func).start()

According to document:

If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.

1 Answer 1

15

Automatic assignment of a new event loop only happens on the main thread. From the source of asyncio DefaultEventLoopPolicy in events.py

def get_event_loop(self):
    """Get the event loop for the current context.

    Returns an instance of EventLoop or raises an exception.
    """
    if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
        self.set_event_loop(self.new_event_loop())

    if self._local._loop is None:
        raise RuntimeError('There is no current event loop in thread %r.'
                            % threading.current_thread().name)

    return self._local._loop

So for a non-main thread, you have to manually set the event loop with asyncio.set_event_loop(asyncio.new_event_loop())

Sign up to request clarification or add additional context in comments.

1 Comment

I faced this issue while launching Ray Workflows from a (non-main) Python thread. Any help is appreciated, see the issue here: discuss.ray.io/t/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.