【发布时间】:2021-09-20 12:35:24
【问题描述】:
我正在使用 multiprocessing.Pool 来加速计算,因为我多次调用一个函数,然后整理结果。这是我的代码的 sn-p:
import multiprocessing
from functools import partial
def Foo(id:int,constant_arg1:str, constant_arg2:str):
custom_class_obj = CustomClass(constant_arg1, constant_arg2)
custom_class_obj.run() # this changes some attributes of the custom_class_obj
if(something):
return None
else:
return [custom_class_obj]
def parallel_run(iters:int, a:str, b:str):
pool = multiprocessing.Pool(processes=k)
## create the partial function obj before passing it to pool
partial_func = partial(Foo, constant_arg1=a, constant_arg2=b)
## create the variable id list
iter_list = list(range(iters))
all_runs = pool.map(partial_func, iter_list)
return all_runs
这会在多处理模块中引发以下错误:
multiprocessing.pool.MaybeEncodingError: Error sending result: '[[<CustomClass object at 0x1693c7070>], [<CustomClass object at 0x1693b88e0>], ....]'
Reason: 'TypeError("cannot pickle 'module' object")'
我该如何解决这个问题?
【问题讨论】:
-
您需要使您的自定义类可腌制。但是,该错误表明您正在尝试返回 module,而不是自定义类。
-
我正在返回一个 CustomClass 对象(如错误消息中“结果”后显示的列表所示)。但是,有没有办法将 Pool 用于不可腌制的类?
-
您将不得不发布您的
CustomClass。见How to create a Minimal, Reproducible Example。
标签: python-3.x multiprocessing pickle python-multiprocessing python-pool