Search code examples
pythonpython-3.xpython-asyncio

Python asyncio difference between loop.create_task and asyncio.run_coroutine_threadsafe


What is the pythonic way to push a coroutine onto an event thread from outside of the event thread?


Solution

  • Updated info:

    Starting from Python 3.7 high-level function asyncio.create_task(coro) was added and can be used instead of both asyncio.ensure_future and loop.create_task to create tasks.

    Python documentation refers to asyncio.create_task(coro) as to "preferred way for creating new Tasks".

    Original answer:

    Just to be clear: usually asyncio runs in single thread. Concurrency provided not by threads, but by using single event loop for running different coroutines.

    If you want to submit coroutine being run concurrently without waiting for it's result you should create task using asyncio.ensure_future (difference from create_task).

    But if your app using multiple threads and you want to submit coroutine being run from one thread to event loop running in another thread, you should use run_coroutine_threadsafe. Here's nice example of running event loop in another thread and submiting coroutine to in from main thread.