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') 

 

完! 

posted @ 2012-01-10 14:49  iTech  阅读(18680)  评论(0编辑  收藏  举报