6

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

1 Answer 1

10

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.

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

3 Comments

Hi @Mikhail, maybe its better to update your answer since now asyncio.create_task(coro) is possible.
@LeonardoRick thanks for noticing! Updated!
@MikhailGerasimov Please add source for "from Python 3.7 asyncio.create_task(coro) should be used"

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.