如果我用一个类变量写一个类,生成两个类对象,并通过使用两个对象之一的方法改变类变量的值,对于另一个对象当然也改变了类变量值.这是我在代码中的意思:
class DemoClass:
ClassVariable = False
def __init__(self):
pass
def do(self):
print(DemoClass.ClassVariable)
DemoClass.ClassVariable = True
class1 = DemoClass()
class1.do() # False
class2 = DemoClass()
class2.do() # True
但是,如果我对 multiprocessing.Process 做同样的事情,它就不起作用了。类变量值只会针对更改它的对象而更改:
import multiprocessing
class DemoProcess(multiprocessing.Process):
ClassVariable = False
def __init__(self):
multiprocessing.Process.__init__(self)
def run(self):
print(DemoProcess.ClassVariable)
DemoProcess.ClassVariable = True
print(DemoProcess.ClassVariable)
if __name__ == '__main__':
process_list = []
p1 = DemoProcess()
process_list.append(p1)
p1.start() # False True
p2 = DemoProcess()
process_list.append(p2)
p2.start() # False True; should be: True True
for p in process_list:
p.join()
代码表现得好像每个进程都生成一个新的类变量。我做错了什么吗?
请您参考如下方法:
在我最初问题的评论者的帮助下,我得出的结论是我还不了解流程是如何工作的。
每个 DemoProcess.start() 都会创建一个新的 Process,不能与其他进程共享其类变量。
我通过使用 Mike McKerns 在评论中提出的 multprocessing.Value 对象解决了这个问题。该对象的值可以与多个进程共享。
import multiprocessing
class DemoProcess(multiprocessing.Process):
def __init__(self, class_variable):
multiprocessing.Process.__init__(self)
self.class_variable = class_variable
def run(self):
print(self.class_variable.value)
with self.class_variable.get_lock():
self.class_variable.value = True
print(self.class_variable.value)
if __name__ == '__main__':
ClassVariable = multiprocessing.Value('b', False)
process_list = []
p1 = DemoProcess(ClassVariable)
process_list.append(p1)
p1.start() # Output: 0 1
p2 = DemoProcess(ClassVariable)
process_list.append(p2)
p2.start() # Output: 1 1
for p in process_list:
p.join()
