为什么 asyncio.wait_for() 需要超时?
Why does asyncio.wait_for() need a timeout?
下面是一个运行两个后台任务的简单异步循环。
他们都进行了简单的计数。第一个永远重要,包裹在
try/except。第二个计数到 5,然后取消第一个并
停止循环。
有两种方法可以确保取消完成-
asyncio.wait([a sequence of futures])
asyncio.wait_for(a single future)
两者都有一个可选的超时。
如果我在没有超时的情况下使用第一种方法,取消完成并且
循环停止。
如果我在没有超时的情况下使用第二种方法,则未来将被取消,但是
程序挂起。
如果我向第二个添加超时,它的行为与第一个相同。
这有什么原因吗?
我使用的是 3.6.0 版本。
import asyncio
from itertools import count
async def counter1():
cnt = count(1)
try:
while True:
print('From 1:', next(cnt))
await asyncio.sleep(1)
except asyncio.CancelledError:
print('counter1 cancelled')
async def counter2():
cnt = count(1)
for i in range(5):
print('From 2:', next(cnt))
await asyncio.sleep(1)
cnt1.cancel()
# await asyncio.wait([cnt1]) # works
# await asyncio.wait_for(cnt1) # hangs
await asyncio.wait_for(cnt1, 1) # works
loop.stop()
loop = asyncio.get_event_loop()
cnt1 = asyncio.ensure_future(counter1())
cnt2 = asyncio.ensure_future(counter2())
loop.run_forever()
我在 comp.lang.python -
收到了以下回复
"The unhandled exception is shown as a warning when the loop exits. It can't be shown prior to that because there could be some other task, even one that hasn't been scheduled yet, that might try to get the result of the counter2 task and handle the exception."
我在 Windows 上测试。我从来没有让 Ctrl-C 在 Windows 上工作,所以我使用 Ctrl-Pause,它使解释器崩溃而不显示任何未决的回溯。
运行 Linux 上的程序并按 Ctrl-C 会显示回溯。如果我一开始就在 Linux 上进行测试,那么就没有必要 post 原来的问题了。
下面是一个运行两个后台任务的简单异步循环。
他们都进行了简单的计数。第一个永远重要,包裹在 try/except。第二个计数到 5,然后取消第一个并 停止循环。
有两种方法可以确保取消完成-
asyncio.wait([a sequence of futures])
asyncio.wait_for(a single future)
两者都有一个可选的超时。
如果我在没有超时的情况下使用第一种方法,取消完成并且 循环停止。
如果我在没有超时的情况下使用第二种方法,则未来将被取消,但是 程序挂起。
如果我向第二个添加超时,它的行为与第一个相同。
这有什么原因吗?
我使用的是 3.6.0 版本。
import asyncio
from itertools import count
async def counter1():
cnt = count(1)
try:
while True:
print('From 1:', next(cnt))
await asyncio.sleep(1)
except asyncio.CancelledError:
print('counter1 cancelled')
async def counter2():
cnt = count(1)
for i in range(5):
print('From 2:', next(cnt))
await asyncio.sleep(1)
cnt1.cancel()
# await asyncio.wait([cnt1]) # works
# await asyncio.wait_for(cnt1) # hangs
await asyncio.wait_for(cnt1, 1) # works
loop.stop()
loop = asyncio.get_event_loop()
cnt1 = asyncio.ensure_future(counter1())
cnt2 = asyncio.ensure_future(counter2())
loop.run_forever()
我在 comp.lang.python -
收到了以下回复"The unhandled exception is shown as a warning when the loop exits. It can't be shown prior to that because there could be some other task, even one that hasn't been scheduled yet, that might try to get the result of the counter2 task and handle the exception."
我在 Windows 上测试。我从来没有让 Ctrl-C 在 Windows 上工作,所以我使用 Ctrl-Pause,它使解释器崩溃而不显示任何未决的回溯。
运行 Linux 上的程序并按 Ctrl-C 会显示回溯。如果我一开始就在 Linux 上进行测试,那么就没有必要 post 原来的问题了。