我想在一个类中使用池(Pool),但是出了问题。我的代码比较长,我创建了一个小型的演示版本来说明问题。如果您能为我提供下面代码的可工作变体,那就太好了。
from multiprocessing import Pool
class SeriesInstance(object):
def __init__(self):
self.numbers = [1,2,3]
def F(self, x):
return x * x
def run(self):
p = Pool()
print p.map(self.F, self.numbers)
ins = SeriesInstance()
ins.run()
输出:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib64/python2.7/multiprocessing/pool.py", line 319, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
然后就停止响应了。
F
包含类成员,会怎么样? - Livne Rosenblumwith Pool() as p:
而不是p = Pool()
。如果我们打算调用run()
多次,则应该将池的创建从方法中移出,以便可以重复使用,而不是每次都创建一个新的。 - Neil Traft