I am studying the module asyncio
of Python
and there is the function run_coroutine_threadsafe which should be run on a thread other than the event loop. Here's my script:
#!usr/bin/python3
# -*- coding: utf-8 -*-
import asyncio
import threading
def target():
print('Iniciou a thread')
#asyncio.set_event_loop(None)
#loop = asyncio.new_event_loop()
asyncio.run_coroutine_threadsafe(blah(), loop)
print('Finalizou a thread')
async def blah():
print('Thread atual:', threading.current_thread().name)
async def main():
thread = threading.Thread(target=target, args=(), kwargs={}, name='Minha Thread')
thread.setDaemon(True)
thread.start()
thread.join()
print('finalizou')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
# Output
Iniciou a thread
Finalizou a thread
finalizando
The problem is that the blah
corotine is never invoked by the run_coroutine_threadsafe
function but I can not find the reason, I even tried to instantiate a new event loop (as you can see in the commented lines) but not even the script it works. What am I missing?