zoukankan      html  css  js  c++  java
  • python类库32[多进程共享高级之Manager]


    Python中进程间共享数据,处理基本的queue,pipe和value+array外,还提供了更高层次的封装。使用multiprocessing.Manager可以简单地使用这些高级接口。 

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

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

    1) Manager的dict,list使用

    import multiprocessing
    import time

    def worker(d, key, value):
        d[key] = value

    if __name__ == '__main__':
        mgr = multiprocessing.Manager()
        d = mgr.dict()
        jobs = [ multiprocessing.Process(target=worker, args=(d, i, i*2))
                 for i in range(10) 
                 ]
        for j in jobs:
            j.start()
        for j in jobs:
            j.join()
        print ('Results:' )
        for key, value in enumerate(dict(d)):
            print("%s=%s" % (key, value))
            
    # the output is :
    #
     Results:
    #
     0=0
    #
     1=1
    #
     2=2
    #
     3=3
    #
     4=4
    #
     5=5
    #
     6=6
    #
     7=7
    #
     8=8
    # 9=9

    上面为manager.dict的使用实例。 

    2)namespace对象没有公共的方法,但是有可写的属性。

    然而当使用manager返回的namespace的proxy的时候,_属性值属于proxy,跟原来的namespace没有关系。
    >>> manager = multiprocessing.Manager()
    >>> Global = manager.Namespace()
    >>> Global.x = 10
    >>> Global.y = 'hello'
    >>> Global._z = 12.3    # this is an attribute of the proxy
    >>> print(Global)
    Namespace(x=10, y='hello') 

    完! 

  • 相关阅读:
    k8s之创建etcd集群
    完美解决微信video视频隐藏控件和内联播放问题
    JS工具库封装:Video转换成Canvas
    H5 video 标签 播放事件
    iSlider 如丝般高性能H5全屏滑动组件
    设计模式之 适配器模式
    c++ STL常用算法使用方法
    快速排序与二分查找
    CLOSE_WAIT TIME_WAIT
    erlang erl文件编译的三种脚本
  • 原文地址:https://www.cnblogs.com/itech/p/2318120.html
Copyright © 2011-2022 走看看