多处理池初始化程序无法酸洗

Multiprocessing Pool initializer fails pickling

我正在尝试使用 multiprocessing.Pool 来实现多线程应用程序。为了共享一些变量,我使用 Queue 作为提示 here:

def get_prediction(data):
    #here the real calculation will be performed
    ....


def mainFunction():
    def get_prediction_init(q):
        print("a")
        get_prediction.q = q

    queue = Queue()
    pool = Pool(processes=16, initializer=get_prediction_init, initargs=[queue,])

if __name__== '__main__':
    mainFunction()

此代码 运行 在 Debian 机器上完美运行,但在另一个 Windows 10 设备上根本无法运行。它因错误

而失败
AttributeError: Can't pickle local object 'mainFunction.<locals>.get_prediction_init'

我真的不知道到底是什么导致了这个错误。我怎样才能解决这个问题,以便我也可以 运行 Windows 设备上的代码?

编辑:如果我在与 mainFunction 相同的级别上创建 get_predediction_init 函数,问题就解决了。只有当我将它定义为内部函数时它才会失败。对不起,我的 post.

中的混乱

问题出在您还没有给我们看的地方。例如,在您显示的 AttributeError 消息中 "mainFunction" 来自哪里是个谜。

这是一个基于您发布的片段的完整的可执行程序。刚刚在 Windows 10 下,在 Python 3.6.1 下(我猜你正在使用 print 语法中的 Python 3),打印 "a" 16次:

import multiprocessing as mp

def get_prediction(data):
    #here the real calculation will be performed
    pass

def get_prediction_init(q):
    print("a")
    get_prediction.q = q

if __name__ == "__main__":
    queue = mp.Queue()
    pool = mp.Pool(processes=16, initializer=get_prediction_init, initargs=[queue,])
    pool.close()
    pool.join()

编辑

而且,根据您的编辑,这个程序对我来说也很好用:

import multiprocessing as mp

def get_prediction(data):
    #here the real calculation will be performed
    pass

def get_prediction_init(q):
    print("a")
    get_prediction.q = q

def mainFunction():
    queue = mp.Queue()
    pool = mp.Pool(processes=16, initializer=get_prediction_init, initargs=[queue,])
    pool.close()
    pool.join()

if __name__ == "__main__":
    mainFunction()

编辑 2

现在您已将 get_prediction_init() 的定义移动到 mainFunction 的正文中。 现在我可以看到你的错误:-)

如图所示,改为在模块级别定义函数。尝试 pickle 本地函数对象可能是一场噩梦。也许有人想与之抗争,但我不想 ;-)