What is the pythonic way to push a coroutine onto an event thread from outside of the event thread?
The method create_task takes a coroutine object as a parameter and returns a Task object, which inherits from asyncio. Future . The call creates the task inside the event loop for the current thread, and starts the task executing at the beginning of the coroutine's code-block.
The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. Application developers should typically use the high-level asyncio functions, such as asyncio.
tl;dr ensure_future let's us execute a coroutine in the background, without explicitly waiting for it to finish. If we need, we can wait for it later or poll for result. In other words, this is a way of executing code in asyncio without await.
You can create multiple threads and run different event loops in each of them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With