Python asyncio: event loop does not seem to stop when stop method is called
Documentation says about event loop class:
This class is not thread safe.
And further:
An event loop runs in a thread and executes all callbacks and tasks in the same thread. [...] To schedule a callback from a different thread, the AbstractEventLoop.call_soon_threadsafe() method should be used. Example:
loop.call_soon_threadsafe(callback, *args)
Seems to be what we need:
import asynciofrom threading import Threadloop = asyncio.get_event_loop()thread = Thread(target=loop.run_forever)thread.start()print('Started!')loop.call_soon_threadsafe(loop.stop) # hereprint('Requested stop!')thread.join()print('Finished!')
Prints:
Started!Requested stop!Finished!