进程间共享数据Manager

一、前言

  进程间的通信Queue()和Pipe(),可以实现进程间的数据传递。但是要使python进程间共享数据,我们就要使用multiprocessing.Manager。

  Manager()返回的manager对象控制了一个server进程,此进程包含的python对象可以被其他的进程通过proxies来访问。从而达到多进程间数据通信且安全。

  Manager支持list,dict,Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event,Queue,Value和Array。

二、multiprocessing.Manager 

from multiprocessing import Process, Manager
import os


def f(d, l):
    d[os.getpid()] = os.getpid()   # 获取进程号
    l.append(os.getpid())
    print(l)


if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()   # 生成一个字典,可以在多个进程间共享和传递
        l = manager.list(range(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)

  进程间的数据默认不共享,那Manager()如何来同步数据?manager对象控制了一个server进程,这个对象有共享数据和让其他进程能访问数据的代理。一个进程修改了数据后,其实并不会通过manager传送数据,作为代理而言,它不知道数据被改变了。为了在共享数据中同步修改的内容,需要在这些代理的容器中,重新声明这个修改过的内容。

Modifications to mutable values or items in dict and list proxies will not be propagated through the manager, because the proxy has no way of knowing when its values or items are modified. To modify such an item, you can re-assign the modified object to the container proxy

  

原文地址:https://www.cnblogs.com/bigberg/p/7999563.html