wisnshaftler
wisnshaftler

Reputation: 33

How to add new co-routine to already running loop in Python asyncio?

I wrote a code like this.

import asyncio
import time
import random

async def secondCoro(myId):
    waiting_time = random.randint(1,5)
    while 1:
        print("i am {} ".format(myId))
        time.sleep(waiting_time)


async def main():
    for i in range (10):
        await loop.create_task(secondCoro(i))
        time.sleep(0.1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

I need to run 10 coroutines at the same time. I gave random sleep time so I think it will be show output like this.

i am 0

i am 2

i am 4

i am 1

i am 2

i am 8

i am 5

But when I run this code it only shows,

i am 0

i am 0

i am 0

Is this achievable? If yes what is problem in my code and how do I fix this? If there are no errors, are there any possible ways to run many co-routines?

Upvotes: 1

Views: 1021

Answers (1)

user4815162342
user4815162342

Reputation: 155046

There are two issues with your code:

  • async code must not block, so instead of calling time.sleep(), you must await asyncio.sleep().

  • "await" means "wait until done", so when you await the tasks in your loop in main(), you never get past the first iteration of the loop because the task never finishes.

There are several ways to fix the second issue. For example, you can call asyncio.gather(), or you can keep the loop as-is, but omit the awaiting of the tasks, and instead await them in a second loop. For example:

async def secondCoro(myId):
    waiting_time = random.randint(1,5)
    while True:
        print("i am {} ".format(myId))
        await asyncio.sleep(waiting_time)

async def main():
    # start all the tasks
    tasks = [asyncio.create_task(secondCoro(i)) for i in range(10)]
    # and await them, which will basically wait forever, while still
    # allowing all the tasks to run
    for t in tasks:
        await t

asyncio.run(main())

Upvotes: 1

Related Questions