为什么 multiprocessing.Process 不能从对象实例中调用方法?无法理解泡菜问题

Why does multiprocessing.Process can not call a method fom an object instance? can not understand that pickle issue

我想从对象实例调用一个方法作为子进程。我在 windows 10.

上使用 python 3.6

让我们创建一个简单的 class:

class A:
     def __init__(self):
         self.a = "A"
     def run(self):
         print("Hello World")

测试一下

>>> a = A()
>>> a.run()
Hello World

然后通过MP调用运行方法

from multiprocessing import Process

if __name__ == "__main__":
    p = Process(target=a.run)
    p.start()

然后出现以下错误:

Traceback (most recent call last):
File "<string>", line 1, in <module>   
File "C:\Users\Synerlink\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
     exitcode = _main(fd)
File "C:\Users\Synerlink\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 115, in _main 
     self = reduction.pickle.load(from_parent) 
AttributeError: Can't get attribute 'A' on <module '__main__' (built-in)>

谁能解释一下它是从哪里来的,如果有办法的话?

不确定您的完整代码是什么样的,但这确实有效。

from multiprocessing import Process


class A:
    def __init__(self):
        self.a = 'A'

    def run(self):
        print('Hello World')

if __name__ == '__main__':
    a = A()
    p = Process(target=a.run)
    p.start()