【问题标题】:Python 3 check if function is executing inside multiprocessing poolPython 3 检查函数是否在多处理池中执行
【发布时间】:2018-12-07 08:45:31
【问题描述】:

如果 f 在 Pool 内,是否可以签入?或者,什么是只捕获特定错误的好捕获?

a = [[1, 2], [1, 2]]

def g(x):
    return x

def f(x):
    try:
        with Pool(2) as p:
            print(p.map(g, x))
    except Exception as e:
        print(type(e))
    return x

with Pool(2) as p:
    print(p.map(f, a))

【问题讨论】:

  • 什么具体错误?为什么要创建两个池?
  • 我猜您正在创建一个使用 Pool 的包,并且您想知道是否有人在他们自己的多处理池中使用您的包?
  • @roganjosh 是的,没错,如果它还没有并行运行,我想加速它。具体错误为 AssertionError
  • 嗯,我不能对此进行类似操作,因为我目前只能访问 Windows。究竟是什么扔了AssertionError?从表面上看,您可以except AssertionError: 并抛出自定义异常,或者让它自然冒泡。
  • __name__ 是子进程的'__mp_main__',所以你可以在 f() 中做if __name__ == '__mp_main__'。如果为 true,则 f() 正在子进程中运行。虽然无法可靠地判断该子进程是否由池生成和控制,但

标签: python python-3.x multiprocessing pool


【解决方案1】:

这对我有用

from multiprocessing import current_process
if "daemon" in current_process()._config:
or
if "ForkPoolWorker" in str(current_process()):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2020-08-14
    • 2016-11-10
    相关资源
    最近更新 更多