python - 多处理:如何在类中定义的函数上使用 Pool.map?

标签 python multiprocessing pickle

当我运行类似的东西时:

from multiprocessing import Pool

p = Pool(5)
def f(x):
     return x*x

p.map(f, [1,2,3])

它工作正常。然而,把它作为一个类的函数:

class calculate(object):
    def run(self):
        def f(x):
            return x*x

        p = Pool()
        return p.map(f, [1,2,3])

cl = calculate()
print cl.run()

给我以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/sw/lib/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "/sw/lib/python2.6/threading.py", line 484, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/sw/lib/python2.6/multiprocessing/pool.py", line 225, in _handle_tasks
    put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

我看过 Alex Martelli 的一篇帖子处理了同样的问题,但不够明确。

最佳答案

我无法使用到目前为止发布的代码,因为使用“multiprocessing.Pool”的代码不适用于 lambda 表达式,并且不使用“multiprocessing.Pool”的代码会产生与工作项一样多的进程。

我修改了代码 s.t.它产生预定义数量的工作人员,并且仅在存在空闲工作人员时才遍历输入列表。我还为 worker s.t. 启用了“守护程序”模式。 ctrl-c 按预期工作。

import multiprocessing


def fun(f, q_in, q_out):
    while True:
        i, x = q_in.get()
        if i is None:
            break
        q_out.put((i, f(x)))


def parmap(f, X, nprocs=multiprocessing.cpu_count()):
    q_in = multiprocessing.Queue(1)
    q_out = multiprocessing.Queue()

    proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
            for _ in range(nprocs)]
    for p in proc:
        p.daemon = True
        p.start()

    sent = [q_in.put((i, x)) for i, x in enumerate(X)]
    [q_in.put((None, None)) for _ in range(nprocs)]
    res = [q_out.get() for _ in range(len(sent))]

    [p.join() for p in proc]

    return [x for i, x in sorted(res)]


if __name__ == '__main__':
    print(parmap(lambda i: i * 2, [1, 2, 3, 4, 6, 7, 8]))

关于python - 多处理:如何在类中定义的函数上使用 Pool.map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3288595/

相关文章:

python - 将 CNN 的输出传递给 BILSTM

neural-network - 不使用 GPU 的 Keras 神经网络模型预测

python - Python有方便解析二进制格式的工具吗?

python - ATIS(航空旅行信息系统)数据集的结构是什么

python - multiprocessing pool.map() 得到 "TypeError: list indices must be integers, not str"

Python多处理管道非常慢(> 100ms)

python - 将类实例列表传递给 multiprocessing.Pool 并并行运行每个类对象的方法函数

python - 在不同的 Windows 版本上使用 pickle 反序列化日期时间对象

python - 在 python 中 pickle 时省略大对象

python - 将大型 csv 插入 MySQL,忽略带有未知字符的行