gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:50:58 25 4
gpt4 key购买 nike

我正在尝试使用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 函数,问题就解决了。仅当我将其定义为内部函数时,它才失败。抱歉我的帖子造成了困惑。

最佳答案

问题出在您没有向我们展示的东西上。例如,您显示的 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 的主体中。 现在我可以看到你的错误:-)

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

关于python - 多处理池初始化程序无法进行酸洗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com