7
Python的futures
包允许我们享受ThreadPoolExecutor
和ProcessPoolExecutor
并行执行任务。DummyExecutor for Python的`期货'
但是,对于调试,暂时用一个虚拟代替真正的并行性是有用的,虚拟代理在主线程中以串行方式执行任务,而不会产生任何线程或进程。
是否有任何执行DummyExecutor
?
Python的futures
包允许我们享受ThreadPoolExecutor
和ProcessPoolExecutor
并行执行任务。DummyExecutor for Python的`期货'
但是,对于调试,暂时用一个虚拟代替真正的并行性是有用的,虚拟代理在主线程中以串行方式执行任务,而不会产生任何线程或进程。
是否有任何执行DummyExecutor
?
像这样的东西应该这样做:可能是没有必要在这种情况下
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我不这么认为,这将创建一个线程,它仍然会与主线程分离。 –
当然你是对的。但是实现一个'Executor'应该不会太复杂,它直接调用可调用对象并返回一个'Future'对象。看看[ThreadPoolExecutor](http://code.google.com/p/pythonfutures/source/browse/trunk/concurrent/futures/thread.py#98)可能会有所帮助 – mata
在你做之前它总是看起来很简单它,但并不总是在你做之后。如果有人已经实现了这一点,我更愿意使用他们的准备实施。 –