Python-多进程共享数据3

多进程共享自定义类方法参考自网上,总结如下,如有错误敬请指正!

1.定义MyClass类继承于python的object类

2.调用BaseManager的register方法注册MyClass类

4.创建BaseManager对象,调用start()方法

5.通过BaseManager.MyClass()的方式创建共享自定义类

自定类中的数据,经过测试,类中数据至少可以是python基本数据类型,或者字典嵌套列表形式。需要注意的是变量不能通过em.salary的形式访问,必须定义方法获取和改变数据。

代码如下:

from multiprocessing import Process, Value, Lock
from multiprocessing.managers import BaseManager
 
class Employee(object):
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        self.data={}
 
    def increase(self):
        self.salary += 100
        self.data.update({'salary':self.salary})
        print(self.data)
 
    def getPay(self):
        return self.name + ':' + str(self.salary)
    def get_data(self):
        return self.data
 
 
def increase_salary(em, lock):
    with lock:
        em.increase()

if __name__ == '__main__':
    # MyManager.register('Employee', Employee)
    # manager = get_my_manager()
    BaseManager.register('Employee', Employee)
    manager = BaseManager()
    manager.start()
    em = manager.Employee('zhangsan', 1000)
    lock = Lock()
    proces = [Process(target=increase_salary, args=(em, lock)) for i in range(10)]
    for p in proces:
        p.start()
    for p in proces:
        p.join()
    print(em.getPay())
    print(em.get_data())

输出如下:

{'salary': 1100}
{'salary': 1200}
{'salary': 1300}
{'salary': 1400}
{'salary': 1500}
{'salary': 1600}
{'salary': 1700}
{'salary': 1800}
{'salary': 1900}
{'salary': 2000}
zhangsan:2000
{'salary': 2000}

参考:

1.https://blog.csdn.net/jacke121/article/details/82658471

2.https://blog.csdn.net/tpoy0099/article/details/52689819

 

 

你可能感兴趣的:(Python-多进程共享数据3)