python - Python 类中的池

标签 python class multiprocessing pool

我想在类中使用 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/

相关文章:

java - 密封类是否在 Java 中强制执行,如果是,如何执行?

java - 我在调用矩形面积的方法时遇到问题

python - 是否可以手动锁定/解锁队列?

Python 多处理和 wxPython 协同工作

python - 编写自定义过滤器的更好方法 | Python-AWS-Boto3

python - 从内置类型派生时如何设置 "the"值?

python - Python numpy数组索引可以为-1吗?

C# - 如何使用具有一个属性的接口(interface)在类之间进行通信

python - 在python的Dask.multiprocessing中有一个共享对象

javascript - 如何在python中使用真正的jquery从网页中提取数据?