python多处理:使用具有共享对象的实例化类的类方法

时间:2013-05-08 18:32:19

标签: python multiprocessing

我是并行处理的新手,但有一个应用程序,它将是有用的。 我有~10-100k对象实例(类型为ClassA),我想使用多处理模块来分配在每个对象上调用特定类方法的工作。我已经阅读了大多数多处理文档和几篇关于调用类方法的帖子,但是我还有一个额外的复杂因素,即ClassA对象都有一个属性指向另一个类型的同一个实例(ClassB),他们可能会这样做添加/删除自己或其他对象。我知道共享状态对并发进程不利,所以我想知道这是否可能。说实话,代理/经理多重处理方法对于了解它们对共享对象的所有影响有点太过分了,但如果有人向我保证我可以让它工作,我会花更多的时间来理解它们。如果没有,这将是设计分布式流程的一课。

以下是我的问题的简化版本:

ClassA:
    def __init__(self, classB_state1, classB_state2, another_obj):
        # Pointers to shared ClassB instances
        self.state1 = classB_state1
        self.state2 = classB_state2
        self.state1.add(self)
        self.object = another_obj

    def run(classB_anothercommonpool):
        # do something to self.object
        if #some property of self.object: 
            classB_anothercommonpool.add(object)
            self.object = None

        self.switch_states()

    def switch_states(self):
        if self in self.state1: 
            self.state1.remove(self)
            self.state2.add(self)

        elif self in self.state2:
            self.state2.remove(self)
            self.state1.add(self)

        else: 
            print "State switch failed!"

ClassB(set): 
# This is essentially a glorified set with a hash so I can have sets of sets.
# If that's a bad design choice, I'd also be interested in knowing why
    def __init__(self, name):
        self.name = name
        super(ClassB, self).__init__()

    def __hash__(self):
        return id(self)

ClassC:
    def __init__(self, property):
        self.property = property

# Define an import-able function for the ClassA method, for multiprocessing
def unwrap_ClassA_run(classA_instance):
    return classA_instance.run(classB_anothercommonpool)

def initialize_states():
    global state1
    global state2
    global anothercommonpool

    state1            = ClassB("state1")
    state2            = ClassB("state2")
    anothercommonpool = ClassB("objpool")

现在,在定义类的相同.py文件中:

from multiprocessing import Pool

def test_multiprocessing():
    initialize_states()

    # There are actually 10-100k classA instances
    object1 = ClassC('iamred')  
    object2 = ClassC('iamblue')
    classA1 = ClassA(state1, state2, object1)
    classA2 = ClassA(state1, state2, object2)

    pool = Pool(processes = 2)
    pool.map(unwrap_ClassA_run, [classA1, classA2])

如果我在解释器中导入此模块并运行test_multiprocessing(),我在运行时没有错误,但是显示“切换状态失败!”消息,如果你检查classA1 / 2对象,它们没有修改它们各自的对象1/2,也没有切换任何一个ClassB状态对象的成员资格(因此ClassA对象没有注册它们是state1集的成员)。谢谢!

0 个答案:

没有答案
相关问题