简体   繁体   中英

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?

Ok, I fixed it thanks to @deceze, I used threading in this way:

for numbers in example:
    t = threading.Thread(target=test_1, args=(numbers,))
    threads.append(t)
    t.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM