0
I’m studying the module asyncio of Python and there is the function run_coroutine_threadsafe which should be executed in a different thread than the event loop. Follow 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 corotina blah is never invoked by the function run_coroutine_threadsafe but I can’t find the reason, I even tried to instantiate a new loop of events (as you can see in the commented lines) but even so the script doesn’t work. What am I missing?
There was no exit in the finished.
– ThiagoO
I switched out the
printforsys.stdout.writebut it didn’t even work out that way.– ThiagoO
I must have been wrong about that. I’m sorry.
– Woss
That I appreciate you trying to help me.
– ThiagoO
From what I understand, reading over the documentation, you don’t need to create a thread for this, the function itself
run_coroutine_threadsafewill run into another thread.– Woss
I thought so, too, but when I make the call
run_coroutine_threadsafeofMainThreadthe printed result is"MainThread", he creates no otherthread, searching found in the documentation a functionrun_in_executorthat makes the creation of anotherthread.– ThiagoO