2012-05-03 6 views
7

Python의 futures 패키지를 사용하면 병렬 작업을 수행 할 때 ThreadPoolExecutorProcessPoolExecutor을 즐길 수 있습니다.Python의`futures`에 대한`DummyExecutor`

그러나 디버깅을 위해 일시적으로 진정한 병렬 처리를 주 스레드에서 직렬 방식으로 작업을 수행하는 더미로 대체하는 것이 유용합니다. 스레드 또는 프로세스를 생성하지 않습니다.

DummyExecutor을 구현 한 곳이 있습니까? 이 같은

+0

@mata 나는 그렇게 생각하지 않는다. 그것은 여전히 ​​메인 쓰레드와 분리 된 하나의 쓰레드를 생성 할 것이다. –

+0

물론 당신 말이 맞습니다. 그렇지만 제출시 직접 호출 객체를 호출하고'Future' 객체를 반환하는'Executor '를 구현하는 것은 너무 복잡해서는 안됩니다. ['ThreadPoolExecutor'] (http://code.google.com/p/pythonfutures/source/browse/trunk/concurrent/futures/thread.py#98)가 도움이 될 수도 있습니다 – mata

+0

하기 전에 항상 간단하게 보입니다. 항상 그래야만하는 것은 아닙니다. 누군가 이미이 기능을 구현했다면 준비된 구현을 사용하는 것이 훨씬 더 바람직합니다. –

답변

5

뭔가를 수행해야합니다

from concurrent.futures import Future, Executor 
from threading import Lock 


class DummyExecutor(Executor): 

    def __init__(self): 
     self._shutdown = False 
     self._shutdownLock = Lock() 

    def submit(self, fn, *args, **kwargs): 
     with self._shutdownLock: 
      if self._shutdown: 
       raise RuntimeError('cannot schedule new futures after shutdown') 

      f = Future() 
      try: 
       result = fn(*args, **kwargs) 
      except BaseException as e: 
       f.set_exception(e) 
      else: 
       f.set_result(result) 

      return f 

    def shutdown(self, wait=True): 
     with self._shutdownLock: 
      self._shutdown = True 


if __name__ == '__main__': 

    def fnc(err): 
     if err: 
      raise Exception("test") 
     else: 
      return "ok" 

    ex = DummyExecutor() 
    print(ex.submit(fnc, True)) 
    print(ex.submit(fnc, False)) 
    ex.shutdown() 
    ex.submit(fnc, True) # raises exception 

잠금 아마이 경우에는 필요하지 않습니다,하지만 그것을 가지고 해치지 않을 수 있습니다.