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()
An event loop is a loop that can register tasks to be executed, execute them, delay or even cancel them and handle different events related to these operations. Generally, we schedule multiple async functions to the event loop. The loop runs one function, while that function waits for IO, it pauses it and runs another.
Run an asyncio Event Loop run_until_complete(<some Future object>) – this function runs a given Future object, usually a coroutine defined by the async / await pattern, until it's complete. run_forever() – this function runs the loop forever. stop() – the stop function stops a running loop.
From the asyncio docs: A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release() .
asyncio. run(main()) asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With