1.数据共享
实现进程之间的数据共享
from multiprocessing import Manager,Process class MyPro(Process): def __init__(self,dic): super().__init__() self.dic = dic def run(self): self.dic[‘count‘] -= 1 print(self.dic) if __name__ == ‘__main__‘: m = Manager() dic = m.dict({‘count‘:100}) p = MyPro(dic) p.start() p.join() print(‘主进程:‘,dic)
结果:
2.但是这种数据共享还是存中安全性问题,当有多个进程同时访问数据的时候,还是会出错,当应用在有多个进程的时候,还是要加锁。
from multiprocessing import Manager,Process,Lock class MyPro(Process): def __init__(self,dic,lock): super().__init__() self.dic = dic self.lock = lock def run(self): self.lock.acquire() self.dic[‘count‘] -= 1 self.lock.release() # print(self.dic) if __name__ == ‘__main__‘: lock = Lock() m = Manager() dic = m.dict({‘count‘:100}) p_list = [] for i in range(50): p = MyPro(dic,lock) p.start() p_list.append(p) for i in p_list: p.join() print(‘主进程:‘,dic)
结果:
原文地址:https://www.cnblogs.com/wangdianchao/p/12080687.html
时间: 2024-10-30 20:42:24