while 循环阻塞异步任务

While loop blocks asyncio tasks

我使用 asyncio 已经有一段时间了,但我对它还是很陌生。我当前的问题是,在尝试使用 asyncio 等待函数的响应时,等待(while 循环)会阻止函数发生。这是总结问题的代码:

import asyncio

response = 0

async def handle(x):
    await asyncio.sleep(0.1)
    return x

async def run():
    global response
    for number in range(1, 21):
        response = await handle(number)
        print(response)
        if response == 10:
            await wait_for_next(response)

async def wait_for_next(x):
    while response == x:
        print('waiting',response,x)
        await asyncio.sleep(0.5)
    print('done')

tasks = [run()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

wait_for_next 应该等待下一个响应,但是 while 循环阻塞了 运行() 函数。我怎样才能阻止这种情况发生?我是否应该使用 loop.run_in_executor,如果是,如何使用?

(我能找到其他几个例子,但它们非常具体,我不明白我们的 problems/solutions 是否相同。)

如前所述,循环卡住了,因为 await wait_for_next(response) 阻塞了执行流程,直到这个协程无法完成。

如果您希望在不阻塞执行流程的情况下启动某些协程,您可以使用 ensure_future 函数将其启动为 asyncio.Task ( 关于任务):

import asyncio

response = 0

async def handle(x):
    await asyncio.sleep(0.1)
    return x

async def run():
    global response
    for number in range(1, 21):
        response = await handle(number)
        print(response)
        if response == 10:

            # run wait_for_next "in background" instead of blocking flow:
            asyncio.ensure_future(wait_for_next(response))

async def wait_for_next(x):
    while response == x:
        print('waiting',response,x)
        await asyncio.sleep(0.5)
    print('done')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())

输出:

1
2
3
4
5
6
7
8
9
10
waiting 10 10
11
12
13
14
done
15
16
17
18
19
20