Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
James Avatar asked Jan 11 '18 22:01

James


People also ask

What is Asyncio Create_task?

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.

What is Asyncio loop?

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.

What does Asyncio Ensure_future do?

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.

Can you have multiple event loops Python?

You can create multiple threads and run different event loops in each of them.


1 Answers

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.

like image 168
Mikhail Gerasimov Avatar answered Sep 23 '22 20:09

Mikhail Gerasimov