Estou estudando o módulo asyncio
do Python
e existe a função run_coroutine_threadsafe que deve ser executado numa thread diferente daquela que está o loop de eventos. Segue meu 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
O problema é que a corotina blah
nunca é invocada pelo função run_coroutine_threadsafe
mas não consigo encontrar o motivo, tentei até mesmo instanciar um novo loop de eventos (como podem ver nas linhas comentadas) mas nem mesmo assim o script funciona. O que estou errando?
print
pelosys.stdout.write
mas nem mesmo assim funcionou.run_coroutine_threadsafe
irá executar em outra thread.