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支持的原生數據類型以下:python

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)
相關文章
相關標籤/搜索