作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用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()
现在您已将 get_prediction_init()
的定义移至 mainFunction
的主体中。 现在我可以看到你的错误:-)
如图所示,改为在模块级别定义函数。尝试腌制本地函数对象可能是一场噩梦。也许有人想与之抗争,但不是我;-)
关于python - 多处理池初始化程序无法进行酸洗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457569/
我是一名优秀的程序员,十分优秀!