进程之间共享数据(数值型):
import multiprocessing
def func(num):
num.value=10.78 #子进程改变数值的值,主进程跟着改变
if __name__=="__main__":
num=multiprocessing.Value("d",10.0) # d表示数值,主进程与子进程共享这个value。(主进程与子进程都是用的同一个value)
print(num.value)
p=multiprocessing.Process(target=func,args=(num,))
p.start()
p.join()
print(num.value)
def
worker(num, mystr, arr):
num.value
*
=
2
mystr.value
=
"ok"
for
i
in
range
(
len
(arr)):
arr[i]
=
arr[i]
*
(
-
1
)
+
1.5
def
dump_vars(num, mystr, arr):
print
'num: '
, num.value
print
'str: '
, mystr[:]
print
'arr: '
, arr[:]
if
__name__
=
=
'__main__'
:
num
=
Value(
'i'
,
5
)
mystr
=
Array(
'c'
,
'just for test'
)
arr
=
Array(
'd'
, [
1.0
,
1.5
,
-
2.0
])
dir
(
str
)
print
'init value'
dump_vars(num, mystr, arr)
ps
=
[Process(target
=
worker, args
=
(num, mystr, arr))
for
x
in
range
(
3
)]
for
p
in
ps:
p.start()
for
p
in
ps:
p.join()
print
print
'after all workers finished'
dump_vars(num, mystr, arr)
进程之间共享数据(数组型):
import multiprocessing
def func(num):
num[2]=9999 #子进程改变数组,主进程跟着改变
if __name__=="__main__":
num=multiprocessing.Array("i",[1,2,3,4,5]) #主进程与子进程共享这个数组
print(num[:])
p=multiprocessing.Process(target=func,args=(num,))
p.start()
p.join()
print(num[:])
进程之间共享数据(dict,list):
import multiprocessing
def func(mydict,mylist):
mydict["index1"]="aaaaaa" #子进程改变dict,主进程跟着改变
mydict["index2"]="bbbbbb"
mylist.append(11) #子进程改变List,主进程跟着改变
mylist.append(22)
mylist.append(33)
if __name__=="__main__":
with multiprocessing.Manager() as MG: #重命名
mydict=multiprocessing.Manager().dict() #主进程与子进程共享这个字典
mylist=multiprocessing.Manager().list(range(5)) #主进程与子进程共享这个List
p=multiprocessing.Process(target=func,args=(mydict,mylist))
p.start()
p.join()
print(mylist)
print(mydict)