我有两个类 A 和 B,尝试通过多处理执行更改自身变量的值并返回 None 值:
A类:
class A:
def __init__(self):
self.value = None
def update_value(self, new_value):
print('Value in class A : ', new_value)
self.value = new_value
def get_value(self):
return self.value
B类:
from A import A
import multiprocessing as mp
instance_1 = A()
instance_2 = A()
p1 = mp.Process(target=instance_1.update_value, args=[100])
p2 = mp.Process(target=instance_2.update_value, args=[200])
p1.start()
p2.start()
p1.join()
p2.join()
print('Value in class B', instance_1.value)
print('Value in class B', instance_2.value)
结果:
Value in class A : 100
Value in class A : 200
Value in class B None
Value in class B None
我想从值变量中获得 A 类和 B 类的相同结果。 怎么能做到呢?
进程不共享相同的内存空间,因此不能在类的同一实例上工作。相反,您应该使用 BaseManager 让不同的进程处理类的同一实例。您将类注册到基本管理器,启动它并通过管理器定义类实例。喜欢这个:
import multiprocessing as mp
from multiprocessing.managers import BaseManager
class A:
def __init__(self):
self.value = None
def update_value(self, new_value):
print('Value in class A : ', new_value)
self.value = new_value
def get_value(self):
return self.value
manager = BaseManager()
manager.register('A', A)
manager.start()
shared1 = manager.A()
shared2 = manager.A()
p1 = mp.Process(target=shared1.update_value, args=(100,))
p2 = mp.Process(target=shared2.update_value, args=(200,))
p1.start()
p2.start()
p1.join()
p2.join()
print('Value in class B', shared1.get_value())
print('Value in class B', shared2.get_value())
输出:
Value in class A : 100
Value in class A : 200
Value in class B 100
Value in class B 200