【问题标题】:Python ~ Importing a class that implements multiprocessing fails on Windows 7Python ~ 在 Windows 7 上导入实现多处理的类失败
【发布时间】:2014-11-01 19:49:21
【问题描述】:

我在一个文件夹中有三个文件:

MultiProcFunctions.py

我们的想法是采用任何函数并将其并行化

import multiprocessing
from multiprocessing import Manager

def MultiProcDecorator(f,*args):

    """
    Takes a function f, and formats it so that results are saved to a shared dict
    """

    def g(procnum,return_dict,*args):
        result = f(*args)
        return_dict[procnum] = result

    g.__module__ = "__main__"

    return g

def MultiProcFunction(f,n_procs,*args):
    """
    Takes a function f, and runs it in n_procs with given args
    """

    manager     = Manager()
    return_dict = manager.dict()

    jobs = []
    for i in range(n_procs):
        p = multiprocessing.Process( target = f, args = (i,return_dict) + args )
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()

    return dict(return_dict)

MultiProcClass.py

定义一个类的文件,该类利用上述函数并行化sq 函数:

from MultiProcFunctions import MultiProcDecorator, MultiProcFunction

def sq(x):
    return x**2

g = MultiProcDecorator(sq)

class Square:
    def __init__(self):
        pass
    def f(self,x):
        return MultiProcFunction(g,2,x)

MultiProcTest.py

最后,我有第三个文件导入上面的类并尝试调用f 方法:

from MultiProcClass import Square

s = Square()
print s.f(2)

但是,这会产生错误:

File "C:\Python27\lib\multiprocessing\managers.py", line 528, in start
    self._address = reader.recv()
EOFError

我在 Windows 7 上,也尝试过:

from MultiProcClass import Square

if __name__ == "__main__":
    s = Square()
    print s.f(2)

在这种情况下,我得到了一个不同的错误:

PicklingError: Can't pickle <function g at 0x01F62530>: it's not found as __main__.g

不知道如何做出正面或反面。在 Ubuntu 12.04 LTS 上我没有遇到任何错误,所有这些都完美无缺;所以这个错误肯定与 Windows 的处理方式有关,但我不能指望它。任何见解都非常感谢!

【问题讨论】:

    标签: python windows class multiprocessing


    【解决方案1】:

    我认为你可以在 Windows 上得到它,因为在 Windows 下你会启动一个新的 Python 进程,而在 Linux 中你会分叉这个进程。这意味着在 Windows 中您需要对函数进行序列化和反序列化,而在 Linux 中可以使用指针。查找函数所需的模块和函数的 nae 以指向它。

    g.__module__ 应该等于 f.__module__

    另外,these answers 可能有助于进一步如何装饰函数以提高可挑选性和可用性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 2011-11-30
      • 2016-04-06
      • 2012-07-11
      • 2012-09-16
      • 2012-11-02
      相关资源
      最近更新 更多