Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

2.5K
Visualizações
RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error

I am having a thread which calls asyncio loops, however this causes the mentioned exception:

RuntimeError: There is no current event loop in thread 'Thread-1'.

This question: RuntimeError: There is no current event loop in thread in async + apscheduler came across the same problem, however they refered to a scheduler which I do not have.

My code is the following:

def worker(ws):
      l1 = asyncio.get_event_loop()
      l1.run_until_complete(ws.start())  


      l2 = asyncio.get_event_loop()
      l2.run_forever()


if __name__ == '__main__':
    ws = Server()
    p = threading.Thread(target=worker,args=(ws,))
    p.start()


    while True:
        try:
            #...do sth
        except KeyboardInterrupt:
            p.join()
            exit() 
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

New thread doesn't have an event loop so you have to pass and set it explicitly:

def worker(ws, loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(ws.start())

if __name__ == '__main__':
    ws = Server()
    loop = asyncio.new_event_loop()
    p = threading.Thread(target=worker, args=(ws, loop,))
    p.start()

Also, p.join() won't terminate your script correctly as you never stop the server so your loop will continue running, presumably hanging up the thread. You should call smth like loop.call_soon_threadsafe(ws.shutdown) before joining the thread, ideally waiting for the server's graceful shutdown.

over 4 years ago · Santiago Trujillo Relatório

0

I had this issue for running a Bokeh Server in a thread. When I tried to create the server = Server({'/': app}, port=0), I would get this error. From the Tornado documentation I found the following...

Class tornado.platform.asyncio.AnyThreadEventLoopPolicy[source]

Event loop policy that allows loop creation on any thread. The default asyncio event loop policy only automatically creates event loops in the main threads. Other threads must create event loops explicitly or asyncio.get_event_loop (and therefore IOLoop.current) will fail. Installing this policy allows event loops to be created automatically on any thread, matching the behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2).

Usage:

asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

http://www.tornadoweb.org/en/stable/asyncio.html#tornado.platform.asyncio.AnyThreadEventLoopPolicy

over 4 years ago · Santiago Trujillo Relatório

0

On Windows with Python 3.7.3, instead of creating the event loop directly in the thread,

I have to:

asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

Otherwise, the problem would persist.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda