我想在类中使用 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
然后挂起。
最佳答案
不幸的是,由于函数传递给工作线程(pickling)的方式,您不能使用实例方法。我的第一个想法是使用 lambda,但结果是内置的 pickler can't serialize those either.不幸的是,解决方案只是在全局命名空间中使用一个函数。正如其他答案中所建议的,您可以使用静态方法并传递 self 以使其看起来更像实例方法。
from multiprocessing import Pool
from itertools import repeat
class SeriesInstance(object):
def __init__(self):
self.numbers = [1,2,3]
def run(self):
p = Pool()
squares = p.map(self.F, self.numbers)
multiples = p.starmap(self.G, zip(repeat(self), [2, 5, 10]))
return (squares, multiples)
@staticmethod
def F(x):
return x * x
@staticmethod
def G(self, m):
return [m *n for n in self.numbers]
if __name__ == '__main__':
print(SeriesInstance().run())
关于python - Python 类中的池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321324/