gpt4 book ai didi

python - while 循环阻塞异步任务

转载 作者:太空狗 更新时间:2023-10-30 01:05:14 25 4
gpt4 key购买 nike

我使用 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 循环阻塞了 run() 函数。我怎样才能阻止这种情况发生?我是否应该使用 loop.run_in_executor,如果是,如何使用?

(我能找到其他几个例子,但它们非常具体,我不明白我们的问题/解决方案是否相同。)

最佳答案

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

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

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

关于python - while 循环阻塞异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46497578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com