2016-10-26 7 views
1

asyncio 차단 프로세스를 처리하는 방법을 테스트하고 싶습니다. asyncio.TimeoutError가 발생하지 않기 때문에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 :] 

답변

2

사용 asyncio.sleep 대신 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 :] 
+0

있었다 어떤 경우 다른 장기 실행 차단 기능 (잠), 어떻게이 5 초 후에 취소되는지 확인합니다 것인가? –

+0

답변을 업데이트했습니다. 희망이 당신을 위해 도움이됩니다. –

+2

@ NarūnasK [loop.run_in_executor] (https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.run_in_executor)와 이에 대한 답변 [실행중인 차단 호출 취소에 대한 대답 집행자] (http://stackoverflow.com/questions/26413613/asyncio-is-it-possible-to-cancel-a-future-been-run-by-an-executor#26414982). – Vincent