2

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()

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, if this is a silly follow up. But would f1 be = asyncio.run_coroutine_threadsafe(coro1, this_threads_event_loop) instead of create_task?
@DrewM Yes, sorry about that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.