Skip to content
Advertisement

Non-blocking launching of concurrent coroutines in Python

I want to execute tasks asynchronously and concurrently. If task1 is running when task2 arrives, task2 is started right away, without waiting for task2 to complete. Also, I would like to avoid callbacks with the help of coroutines.

Here’s a concurrent solution with callbacks:

JavaScript

Its output:

JavaScript

And here’s my effort to get rid of callbacks:

JavaScript

Output:

JavaScript

In this case initial thread won’t be able to go further than loop.run_forever() and hence won’t be able to accept new tasks.

So, here’s my question: is there a way to simultaneously:

  • execute tasks concurrently;
  • be able to accept new tasks and schedule them for execution right away (along with already running taks);
  • use coroutines and code without callbacks.

Advertisement

Answer

The second bullet from your question can be met by running asyncio in a dedicated thread and using asyncio.run_coroutine_threadsafe to schedule coroutines. For example:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement