代码之家  ›  专栏  ›  技术社区  ›  Amir

将函数或类实例传递给multiprocessing.Process的“target”参数是否安全,而不存在密集复制的风险?

  •  2
  • Amir  · 技术社区  · 6 年前

    我想知道是否有可能将另一个类的函数传递给一个 multiprocessing.Process 作为论据?请注意,我将在基于Unix的机器上运行此代码,因此 Process fork 而不是 spawn . 举个例子:

    #class1.py
    from class3 import Class3
    class Class1(object):
        def __init__(self):
            self.class3Instance = Class3()
    
        def func1(self):
            self.class3Instance.func3()
    
    #class3.py
    import numpy as np
    import pandas
    import cv2 # OpenCV library
    # there are many other things that I am importing here
    
    class Class3(object):
        def __init__(self):
            pass
    
        def func3(self):
            np.random.seed(1)
            print ('func3 changed the random seed')
    
    #class2.py
    import numpy as np
    class Class2(object):
        def __init__(self):
            pass
    
        def func2(self, funcInput):
            funcInput()
    
    #main.py
    from class1 import Class1
    from class2 import Class2
    
    class1Instance = Class1()
    class2Instance = Class2()
    from multiprocessing import Process
    
    class2Process = Process(target=class2Instance.func2, kwargs={'funcInput': class1Instance.func1})
    class2Process.start()
    class2Process.join()
    

    这个例子在这么小的范围内似乎很管用,但恐怕 将无法

    1 回复  |  直到 6 年前
        1
  •  3
  •   ShadowRanger    6 年前

    multiprocessing.Process ,用于 fork 模式下,将不需要pickle绑定方法(这将需要pickle实例),因此所付出的前期成本最小。这个AFAICT没有文档化的保证,但是CPython使用fork的实现没有做到这一点,他们也没有理由这么做,所以我不能看到他们在没有任何收获的情况下拿走这个特性。

    Process 通常会与父进程共享几个页面。

    还要注意的是 ,在 模式,是你唯一能从中受益的时候。 forkserver spawn multiprocessing.Pool 方法如 apply / apply_async 以及各种 map -相似函数 总是 pickle要调用的函数及其参数(因为工作进程不知道在分叉时它们将被要求运行什么任务,而且对象可能在分叉后发生了更改,所以每次都会重新调用它们)。