我不熟悉并行处理,但有一个应用程序,它将是有用的。
我有大约10-100k个对象实例(类型为ClassA
),我想使用多处理模块来分配对每个对象调用特定类方法的工作。我已经阅读了大多数多处理文档和一些关于调用类方法的文章,但是我还有一个额外的复杂性,即ClassA对象都有一个指向另一个类型(ClassB
)的同一个实例的属性,它们可以向/从中添加/删除自身或其他对象。我知道共享状态不利于并发进程,所以我想知道这是否可能。老实说,Proxy/Manager mutliprocessing方法对我来说有点过头了,无法理解它们对共享对象的所有影响,但是如果有人向我保证我可以使用它,我会花更多的时间来理解它们。如果没有,这将是设计分布式进程的一堂课。在
以下是我的问题的简化版本:
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文件中:
^{pr2}$如果我在解释器中导入此模块并运行test趵multiprocessing(),则在运行时不会出现错误,但“开关状态失败!”将显示消息,如果您检查类A1/2对象,则它们没有修改各自的对象1/2,也没有切换任何一个类B状态对象的成员身份(因此,类对象不会注册为state1集合的成员)。谢谢!在
目前没有回答
相关问题 更多 >
编程相关推荐