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

标签 python debugging concurrency future concurrent.futures

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/

相关文章:

php - Python 中 PHP 对象的相同哈希值

python - 如何将 Django 模型发送到带有附加自定义字段的模板中?

python - GetSearch还是SreamListener? Python

concurrency - 不同输入数据的 Goroutine 执行时间

python - tensorflow 类型错误 : Value passed to parameter 'shape' has DataType float32 not in list of allowed values: int32, int64

c++ - 如何远程调试 Mac 桌面应用程序

c# - 如何查看在不同计算机上创建的 Visual Studio VSP 文件?

javascript - 如何调试 "Expression Changed After It Has Been Checked"错误?

objective-c - 是否可以在操作系统或编程语言级别强制执行无共享多线程? (OSX, Objective-C )

java - 并发网络爬虫通常将访问过的 URL 存储在并发映射中,还是使用同步来避免两次抓取相同的页面?