[英]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.我需要同时运行 10 个协程。 I gave random sleep time so I think it will be show output like this.
我给了随机睡眠时间,所以我认为它会像这样显示 output 。
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?
如果没有错误,是否有任何可能的方法来运行许多协程?
There are two issues with your code:您的代码有两个问题:
async code must not block, so instead of calling time.sleep()
, you must await asyncio.sleep()
.异步代码不能阻塞,因此您必须等待 asyncio.sleep() 而不是调用
time.sleep()
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. “await”的意思是“等到完成”,所以当你在 main() 中等待循环中的任务时,你永远不会超过循环的第一次迭代,因为任务永远不会完成。
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.例如,您可以调用
asyncio.gather()
,或者您可以保持循环不变,但省略任务的等待,而是在第二个循环中等待它们。 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.