[英]Asyncio Gathering a while loop
This is a simplified version of my code, but the the problem is the same:这是我的代码的简化版本,但问题是相同的:
import asyncio
example = ["1", "2", "3", "4", "5"]
def test_1(numbers):
while True:
print(numbers)
tasks = []
async def test_2():
for numbers in example:
try:
tasks.append(test_1(numbers))
except:
pass
try:
await asyncio.gather(*tasks)
except:
pass
asyncio.run(test_2())
What I'm trying to do is printing all items at the same time in a while loop, but when I run the code it only prints the first item since it's looped, is there a way to fix it?我想要做的是在 while 循环中同时打印所有项目,但是当我运行代码时,它只打印第一个项目,因为它是循环的,有没有办法解决它?
Ok, I fixed it thanks to @deceze, I used threading in this way:好的,感谢@deceze,我修复了它,我以这种方式使用线程:
for numbers in example:
t = threading.Thread(target=test_1, args=(numbers,))
threads.append(t)
t.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.