【发布时间】:2016-10-26 15:08:17
【问题描述】:
我想测试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 :]
【问题讨论】:
标签: python python-3.4 python-asyncio