gpt4 book ai didi

python - `DummyExecutor` 用于 Python 's ` future `

转载 作者:太空狗 更新时间:2023-10-29 17:07:21 26 4
gpt4 key购买 nike

Python 的 futures 包允许我们使用 ThreadPoolExecutorProcessPoolExecutor 并行执行任务。

但是,为了调试,有时用虚拟并行临时替换真正的并行很有用,虚拟并行在主线程中以串行方式执行任务,而不会产生任何线程或进程。

有没有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

在这种情况下可能不需要锁定,但拥有它也无妨。

关于python - `DummyExecutor` 用于 Python 's ` future `,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10434593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com