一个典型的asyncio协程异步代码


import asyncio


async def hello(num):

    while num <= 30:
        print(f'num = {num}')
        await asyncio.sleep(1)
        print(f'sleep done - {num}')
        num += 1


coroutine_num = 3
tasks = []
loop = asyncio.get_event_loop()
for i in range(coroutine_num):
    tasks.append(hello(0))
loop.run_until_complete(asyncio.wait(tasks))
loop.close()



D:\pythonProject\venv\Scripts\python.exe D:/pythonProject/test/testWhileInAsyncio.py
num = 0
num = 0
num = 0
sleep done - 0
num = 1
sleep done - 0
num = 1
sleep done - 0
num = 1
sleep done - 1
num = 2
sleep done - 1
num = 2
sleep done - 1
num = 2
sleep done - 2
num = 3
sleep done - 2
num = 3
sleep done - 2
num = 3
sleep done - 3
num = 4
sleep done - 3
num = 4
sleep done - 3
num = 4
sleep done - 4
num = 5
sleep done - 4
num = 5
sleep done - 4
num = 5
sleep done - 5
num = 6
sleep done - 5
num = 6
sleep done - 5
num = 6
sleep done - 6
num = 7
sleep done - 6
num = 7
sleep done - 6
num = 7
sleep done - 7
num = 8
sleep done - 7
num = 8
sleep done - 7
num = 8
sleep done - 8
num = 9
sleep done - 8
num = 9
sleep done - 8
num = 9
sleep done - 9
num = 10
sleep done - 9
num = 10
sleep done - 9
num = 10
sleep done - 10
num = 11
sleep done - 10
num = 11
sleep done - 10
num = 11
sleep done - 11
num = 12
sleep done - 11
num = 12
sleep done - 11
num = 12
sleep done - 12
num = 13
sleep done - 12
num = 13
sleep done - 12
num = 13
sleep done - 13
num = 14
sleep done - 13
num = 14
sleep done - 13
num = 14
sleep done - 14
num = 15
sleep done - 14
num = 15
sleep done - 14
num = 15
sleep done - 15
num = 16
sleep done - 15
num = 16
sleep done - 15
num = 16
sleep done - 16
num = 17
sleep done - 16
num = 17
sleep done - 16
num = 17
sleep done - 17
num = 18
sleep done - 17
num = 18
sleep done - 17
num = 18
sleep done - 18
num = 19
sleep done - 18
num = 19
sleep done - 18
num = 19
sleep done - 19
num = 20
sleep done - 19
num = 20
sleep done - 19
num = 20
sleep done - 20
num = 21
sleep done - 20
num = 21
sleep done - 20
num = 21
sleep done - 21
num = 22
sleep done - 21
num = 22
sleep done - 21
num = 22
sleep done - 22
num = 23
sleep done - 22
num = 23
sleep done - 22
num = 23
sleep done - 23
num = 24
sleep done - 23
num = 24
sleep done - 23
num = 24
sleep done - 24
num = 25
sleep done - 24
num = 25
sleep done - 24
num = 25
sleep done - 25
num = 26
sleep done - 25
num = 26
sleep done - 25
num = 26
sleep done - 26
num = 27
sleep done - 26
num = 27
sleep done - 26
num = 27
sleep done - 27
num = 28
sleep done - 27
num = 28
sleep done - 27
num = 28
sleep done - 28
num = 29
sleep done - 28
num = 29
sleep done - 28
num = 29
sleep done - 29
num = 30
sleep done - 29
num = 30
sleep done - 29
num = 30
sleep done - 30
sleep done - 30
sleep done - 30

Process finished with exit code 0