뭔가를 수행해야합니다
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
잠금 아마이 경우에는 필요하지 않습니다,하지만 그것을 가지고 해치지 않을 수 있습니다.
@mata 나는 그렇게 생각하지 않는다. 그것은 여전히 메인 쓰레드와 분리 된 하나의 쓰레드를 생성 할 것이다. –
물론 당신 말이 맞습니다. 그렇지만 제출시 직접 호출 객체를 호출하고'Future' 객체를 반환하는'Executor '를 구현하는 것은 너무 복잡해서는 안됩니다. ['ThreadPoolExecutor'] (http://code.google.com/p/pythonfutures/source/browse/trunk/concurrent/futures/thread.py#98)가 도움이 될 수도 있습니다 – mata
하기 전에 항상 간단하게 보입니다. 항상 그래야만하는 것은 아닙니다. 누군가 이미이 기능을 구현했다면 준비된 구현을 사용하는 것이 훨씬 더 바람직합니다. –