gpt4 book ai didi

python - asyncio.TimeoutError 永远不会引发

转载 作者:行者123 更新时间:2023-12-01 03:36:40 24 4
gpt4 key购买 nike

我想测试 asyncio 如何处理阻塞进程。

我的代码一定有问题,因为 asyncio.TimeoutError 从未引发:

import asyncio, random, time

q = asyncio.Queue()

MAX_WAIT = 5

@asyncio.coroutine
def blocking_task(sec):
print('This task will sleep {} sec.'.format(sec))
time.sleep(sec)

@asyncio.coroutine
def produce():
while True:
q.put_nowait(random.randint(1,10))
yield from asyncio.sleep(0.5 + random.random())

@asyncio.coroutine
def consume():
while True:
value = yield from q.get()
try:
yield from asyncio.wait_for(blocking_task(value), MAX_WAIT)
except asyncio.TimeoutError:
print('~/~ Job has been canceled !!')
else:
print('=/= Job has been done :]')


loop = asyncio.get_event_loop()
asyncio.ensure_future(produce())
asyncio.ensure_future(consume())
loop.run_forever()

此代码产生以下输出:

$ ./tst3.py 
This task will sleep 2 sec.
=/= Job has been done :]
This task will sleep 1 sec.
=/= Job has been done :]
This task will sleep 7 sec.
=/= Job has been done :]

最佳答案

Use asyncio.sleep instead of sleep

TimeoutError of asynciobuildin TimeoutError 不同。这就是为什么您不能使用 time.sleep 来触发此错误。要在asyncio.coroutine中触发TimeoutError,只能使用asyncio模块实现的定时器。

@asyncio.coroutine
def blocking_task(sec):
print('This task will sleep {} sec.'.format(sec))
yield from asyncio.sleep(sec)

结果

This task will sleep 10 sec.
~/~ Job has been canceled !!
This task will sleep 3 sec.
=/= Job has been done :]
This task will sleep 4 sec.
=/= Job has been done :]
This task will sleep 2 sec.
=/= Job has been done :]
This task will sleep 7 sec.
~/~ Job has been canceled !!
This task will sleep 2 sec.
=/= Job has been done :]

关于python - asyncio.TimeoutError 永远不会引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265882/

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