[英]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循環會阻塞run()函數。 我怎樣才能阻止這種情況呢? 我應該使用loop.run_in_executor嗎?
(我可以找到其他一些例子,但是它們非常具體,我不明白我們的問題/解決方案是否相同。)
如前所述,循環停滯是因為await wait_for_next(response)
阻塞了執行流,直到協同程序無法完成為止。
如果您希望在不阻止執行流程的情況下啟動某些協程,則可以使用ensure_future
函數將其作為asyncio.Task (有關任務的更多信息) 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.