Reputation: 452
In this minimal example, I expect the program to print foo
and fuu
as the tasks are scheduled.
import asyncio
async def coroutine():
while True:
print("foo")
async def main():
asyncio.create_task(coroutine())
#asyncio.run_coroutine_threadsafe(coroutine(),asyncio.get_running_loop())
while True:
print("fuu")
asyncio.run(main())
The program will only write fuu
.
My aim is to simply have two tasks executing concurrently, but it seems like the created task is never scheduled.
I also tried using run_coroutine_threadsafe
with no success.
If I add await asyncio.sleep(1)
to the main. The created task takes the execution and the program will only write foo
.
What I am supposed to do to run two tasks simultaneously using asyncio ?
Upvotes: 2
Views: 842
Reputation: 2180
I love this question and the explanation of this question tells how asyncio and python works.
Spoilers - It works similar to Javascript single threaded runtime.
So, let's look at your code. You only have one main thread running which would be continuously running since python scheduler don't have to switch between threads. Now, the thing is, your main thread that creates a task actually creates a coroutine(green threads, managed by python scheduler and not OS scheduler) which needs main thread to get executed.
Now the main thread is never free, since you have put while True, it is never free to execute anything else and your task never gets executed because python scheduler never does the switching because it is busy executing while True code.
The moment you put sleep, it detects that the current task is sleeping and it does the context switching and your coroutine kicks in.
My suggestion. if your tasks are I/O heavy, use tasks/coroutines and if they are CPU heavy which is in your case (while True
), create either Python Threads or Processes and then the OS scheduler will take care of running your tasks, they will get CPU slice to run while True
.
Upvotes: 2