欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python multiprocessing.Manager介紹和實(shí)例(進(jìn)程間共享數(shù)據(jù))

 更新時(shí)間:2014年11月21日 09:25:37   投稿:junjie  
這篇文章主要介紹了Python multiprocessing.Manager介紹和實(shí)例(進(jìn)程間共享數(shù)據(jù)),本文介紹了Manager的dict、list使用例子,同時(shí)介紹了namespace對(duì)象,需要的朋友可以參考下

Python中進(jìn)程間共享數(shù)據(jù),處理基本的queue,pipe和value+array外,還提供了更高層次的封裝。使用multiprocessing.Manager可以簡(jiǎn)單地使用這些高級(jí)接口。

Manager()返回的manager對(duì)象控制了一個(gè)server進(jìn)程,此進(jìn)程包含的python對(duì)象可以被其他的進(jìn)程通過(guò)proxies來(lái)訪問(wèn)。從而達(dá)到多進(jìn)程間數(shù)據(jù)通信且安全。

Manager支持的類型有l(wèi)ist,dict,Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event,Queue,Value和Array。

1) Manager的dict,list使用

復(fù)制代碼 代碼如下:

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的使用實(shí)例。

2)namespace對(duì)象沒(méi)有公共的方法,但是有可寫的屬性。

然而當(dāng)使用manager返回的namespace的proxy的時(shí)候,_屬性值屬于proxy,跟原來(lái)的namespace沒(méi)有關(guān)系。

復(fù)制代碼 代碼如下:

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

相關(guān)文章

最新評(píng)論