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

zim*_*rol 5 python pool multiprocessing

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

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()
Run Code Online (Sandbox Code Playgroud)

该代码可以在Debian计算机上完美运行,但在另一台Windows 10设备上则根本无法运行。它因错误而失败

AttributeError: Can't pickle local object 'mainFunction.<locals>.get_prediction_init'
Run Code Online (Sandbox Code Playgroud)

我真的不知道到底是什么引起了错误。如何解决该问题,以便我也可以在Windows设备上运行代码?

编辑:如果我get_predediction_init在与相同的级别上创建函数,则可以解决问题mainFunction。仅当我将其定义为内部函数时,它才失败。对不起,我的帖子混乱。

Tim*_*ers 3

问题出在你没有向我们展示的东西上。例如,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()
Run Code Online (Sandbox Code Playgroud)

编辑

而且,根据您的编辑,这个程序也适合我:

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()
Run Code Online (Sandbox Code Playgroud)

编辑2

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

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