首页 > 代码库 > 进程间通讯-3(Manager)

进程间通讯-3(Manager)

Manager 可以实现列表,字典,变量,锁,信号量,事件等的数据之间的共享。Manager已经默认加锁了。

 

from multiprocessing import Process, Manager
import os
def f(d, l):
    d[1] = ‘1‘
    d[‘2‘] = 2
    d[0.25] = None
    d[os.getpid()]=os.getpid()
    l.append(os.getpid()) #获取进程号
    print(l)

if __name__ == ‘__main__‘:
    with Manager() as manager: #manager=Manager()
        d = manager.dict() #生成一个在多个进程之间可以传递共享的字典,
        l = manager.list(range(5)) #生成一个可在多个进程之间传递和共享的列表,已经存放了5个元素
        p_list = [] #存放结果

        for i in range(10):
            p = Process(target=f, args=(d, l))
            p.start()
            p_list.append(p)

        for res in p_list: #等待结果
            res.join()

        print(d)
        print(l)

运行结果:

 

C:\abccdxddd\Oldboy\python-3.5.2-embed-amd64\python.exe C:/abccdxddd/Oldboy/Py_Exercise/Day10/Manager_tes.py
[0, 1, 2, 3, 4, 12836]
[0, 1, 2, 3, 4, 12836, 11324]
[0, 1, 2, 3, 4, 12836, 11324, 15000]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960, 14504]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960, 14504, 4208]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960, 14504, 4208, 12984]
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960, 14504, 4208, 12984, 11724]
{0.25: None, 1: ‘1‘, 12836: 12836, 13960: 13960, 11724: 11724, 12984: 12984, 14476: 14476, ‘2‘: 2, 9576: 9576, 4208: 4208, 14504: 14504, 15000: 15000, 11324: 11324}
[0, 1, 2, 3, 4, 12836, 11324, 15000, 9576, 14476, 13960, 14504, 4208, 12984, 11724]

Process finished with exit code 0

 

进程间通讯-3(Manager)