Python 进程之间共享数据(全局变量)
进程之间共享数据(数值型):
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)
进程之间共享数据(数组型):
import multiprocessing
import ctypes
def func(num):
num[2]=9999 #子进程改变数组,主进程跟着改变
if __name__=="__main__":
num=multiprocessing.Array(ctypes.c_int,[1,2,3,4,5]) #主进程与子进程共享这个数组
print(num[:])
p=multiprocessing.Process(target=func,args=(num,))
p.start()
p.join()
print(num[:])
ctypes支持的原生数据类型如下:
ctypes类型 | C 类型 | Python 类型 |
---|---|---|
c_char | char | 1-character string |
c_wchar | wchar_t | 1-character unicode string |
c_byte | char | int/long |
c_ubyte | unsigned char | int/long |
c_bool | bool | bool |
c_short | short | int/long |
c_ushort | unsigned short | int/long |
c_int | int | int/long |
c_uint | unsigned int | int/long |
c_long | long | int/long |
c_ulong | unsigned long | int/long |
c_longlong | __int64 or longlong | int/long |
c_ulonglong | unsigned __int64 or unsigned long long | int/long |
c_float | float | float |
c_double | double | float |
c_longdouble | long double float | float |
c_char_p | char * | string or None |
c_wchar_p | wchar_t * | unicode or None |
c_void_p | void * | int/long or None |
进程之间共享数据(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)