1.可以通过multiprocessing中Value,Array传递:
from multiprocessing import Pool,Array,Value
import time
#i:int c:char f:float d:double
val1 = Value('i', 0)
val2 = Value('d', 0.0)
val3 = Value('c', b'A')
#等价于val3=Value('c',65)
array = Array('i', [0 for _ in range(20)
def func(i):
val1 = i
array[i] = i
print(val1, [i for _ in array])
time.sleep(0.1)
if __name__=='__main__':
p=Pool(5)
p.map(func,range(20))
p.close()
p.join()
2.使用Manager(推荐)中 dict,list ,Array,Value
from multiprocessing import Pool,freeze_support,Manager
import time
def func(dict):
if dict[0]<10:
dict[0]+=1
time.sleep(1)
print(id(dict),dict.values())
def func2(val):
#val+=1 出错unsupported operand type(s) for +=: 'ValueProxy' and 'int'
#应用val.value调用值
val.value+=1
time.sleep(1)
print(value)
if __name__=='__main__':
#Manager需放在 if __name__=='__main__'下
manager=Manager()
a=manager.Array('i',range(20))
d=manager.dict({0:0})
p=Pool(5)
p.map(func,[d]*20)
p.close()
p.join()
print(d.values())