Value、Array是通过共享内存的方式共享数据
Manager是通过共享进程的方式共享数据。
队列直接插入元祖,对象也是可以的:event需要是manager的,这个对象可以在多个进程里面共享
em = SBD_msg(cam_no, frame, event_obj)
mlock.acquire()
data_queue.put(em)
Value\Array
实例代码:
import multiprocessing
#Value/Array
def func1(a,arr):
a.value=3.14
for i in range(len(arr)):
arr[i]=-arr[i]
if __name__ == '__main__':
num=multiprocessing.Value('d',1.0)#num=0
arr=multiprocessing.Array('i',range(10))#arr=range(10)
p=multiprocessing.Process(target=func1,args=(num,arr))
p.start()
p.join()
print num.value
print arr[:]
执行结果:
3.14
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
Manager管理的共享数据类型有:Value、Array、dict、list、Lock、Semaphore等等,同时Manager还可以共享类的实例对象。
实例代码:
from multiprocessing import Process,Manager
def func1(shareList,shareValue,shareDict,lock):
with lock:
shareValue.value+=1
shareDict[1]='1'
shareDict[2]='2'
for i in xrange(len(shareList)):
shareList[i]+=1
if __name__ == '__main__':
manager=Manager()
list1=manager.list([1,2,3,4,5])
dict1=manager.dict()
array1=manager.Array('i',range(10))
value1=manager.Value('i',1)
lock=manager.Lock()
proc=[Process(target=func1,args=(list1,value1,dict1,lock)) for i in xrange(20)]
for p in proc:
p.start()
for p in proc:
p.join()
print list1
print dict1
print array1
print value1
执行结果:
[21, 22, 23, 24, 25]
{1: '1', 2: '2'}
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Value('i', 21)
通过Manager进程间共享实例对象:
from multiprocessing import Process,Value,Lock
from multiprocessing.managers import BaseManager
class Employee(object):
def __init__(self,name,salary):
self.name=name
self.salary=Value('i',salary)
def increase(self):
self.salary.value+=100
def getPay(self):
return self.name+':'+str(self.salary.value)
class MyManager(BaseManager):
pass
def Manager2():
m=MyManager()
m.start()
return m
MyManager.register('Employee',Employee)
def func1(em,lock):
with lock:
em.increase()
if __name__ == '__main__':
manager=Manager2()
em=manager.Employee('zhangsan',1000)
lock=Lock()
proces=[Process(target=func1,args=(em,lock))for i in xrange(10)]
for p in proces:
p.start()
for p in proces:
p.join()
print em.getPay()