Federico K
Federico K

Reputation: 31

Trouble with Python3 Asyncio creating tasks

Have worked through most examples but am still learning async in Python. I am having trouble why this example of code will not print "i am async".

import asyncio
from threading import Thread

async def cor1():
   print("i am async!")

def myasync(loop):
   print("Async running")
   loop.run_forever()
   print("Async ended?")

def main():
   this_threads_event_loop = asyncio.get_event_loop()
   t_1 = Thread(target=myasync, args=(this_threads_event_loop,));
   t_1.start()
   print("begining the async loop")
   t1 = this_threads_event_loop.create_task(cor1())
   print("Finsihed cor1")

main()

Upvotes: 2

Views: 60

Answers (1)

user4815162342
user4815162342

Reputation: 154846

Your code attempts to submit tasks to the event loop from a different thread. To do that, you must use run_coroutine_threadsafe:

def main():
   loop = asyncio.get_event_loop()
   # start the event loop in a separate thread
   t_1 = Thread(target=myasync, args=(loop,));
   t_1.start()
   # submit the coroutine to the event loop running in the
   # other thread
   f1 = asyncio.run_coroutine_threadsafe(cor1(), loop)
   # wait for the coroutine to finish, by asking for its result
   f1.result()
   print("Finsihed cor1")

Please note that combining asyncio and threads should only be done in special circumstances, such as when introducing asyncio to a legacy application where the new functionality needs to be added gradually. If you are writing new code, you almost certainly want the main to be a coroutine, run from top-level using asyncio.run(main()).

To run a legacy synchronous function from asyncio code, you can always use run_in_executor.

Upvotes: 2

Related Questions