I have a simple piece of code driving me crazy for a while. I have posted this question some days ago asking create_task is not working with input. Now I have figured out something related to this. I am running event loop in a separate thread and pushing tasks in it. Very straight forward code.
import asyncio
import threading
async def printer(message):
print(f'[printer] {message}')
def loop_runner(loop):
loop.run_forever()
if __name__ == '__main__':
event_loop = asyncio.get_event_loop()
t = threading.Thread(target=loop_runner, args=(event_loop,))
t.start()
for m in ['hello', 'world', 'foo', 'bar']:
print(f'[loop running ?] {event_loop.is_running()}')
event_loop.create_task(printer(m))
Nothing gets printed but these log messages.
[loop running ?] True
[loop running ?] True
[loop running ?] True
[loop running ?] True
Now if I block in event loop thread and let it run after a pause like this.
def loop_runner(loop):
time.sleep(1 / 1000)
loop.run_forever()
Everything works and this gets printed
[loop running ?] False
[loop running ?] False
[loop running ?] False
[loop running ?] False
[printer] hello
[printer] world
[printer] foo
[printer] bar
From surface it looks like tasks created in running event loop do not get executed. But why is that?
I have not seen anything regarding this in documentation. In most of the examples I have seen on internet people are creating tasks in loop from other coroutines and awaiting for them. But I think it is legal to use create tasks outside coroutine if you do not want to await for them.