Ziqi Liu
Ziqi Liu

Reputation: 3171

Python3 asyncio There is no current event loop in thread when spawn a new thread

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.

Upvotes: 8

Views: 10496

Answers (1)

syfluqs
syfluqs

Reputation: 678

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())

Upvotes: 15

Related Questions