Python?multiprocessing?共享對象的示例代碼
在 Python 中,共享內存多處理由連接多個處理器組成,但這些處理器必須能夠直接訪問系統(tǒng)的主內存。 這將允許所有連接的處理器訪問它們使用或創(chuàng)建的其他處理器數據。
在多進程中使用 Python 共享內存對象
在 Python 中使用 multiprocessing,一個新的進程可以獨立運行并擁有自己的內存空間。 通過查看下面的示例,讓我們詳細了解使用 Python 的共享對象多處理。
示例代碼:
import multiprocessing #an empty array globally declared answer = [] def square_numbers(mynumbers): #for squaring array elements, a function has been used global answer #appending square numbers to a global array for n in mynumbers: answer.append(n * n) #print a global array for generating an answer print("Answer using first process: {}".format(answer)) if __name__ == "__main__": #input array mynumbers = [5,10,15] #new process has been created p = multiprocessing.Process(target=square_numbers, args=(mynumbers,)) #process begins here p.start() #wait unless a process is completed p.join() #print a global array for generating an answer print("Answer using main program: {}".format(answer))
輸出:
Answer using first process: [25, 100, 225]
Answer using main program: []
我們使用上面的例子在兩個地方打印了全局數組答案。
進程 p 調用 square_numbers 函數,以便在內存空間中為進程 p 更改數組元素。
主程序在進程 p 完成后運行,我們將在內存空間中得到一個空數組作為答案。
Python 中的多處理提供了值對象和一個數組,用于在多個進程之間共享數據。
示例代碼:
import multiprocessing def square_data(mydata, answer, square_sum): #a function has been made for squaring of given data #appending squares of mydata to the given array for ix, n in enumerate(mydata): answer[ix] = n * n #sum the square values square_sum.value = sum(answer) #print array of squared values for process p print("Answer in process p: {}".format(answer[:])) # print the sum of squared values for process p print("Sum of squares values in process p: {}".format(square_sum.value)) if __name__ == "__main__": #here, we input the data mydata = [1,2,3] #an array has been created for the int data type for three integers answer = multiprocessing.Array('i', 3) #value has been created for int data type square_sum = multiprocessing.Value('i') #new process has been created p = multiprocessing.Process(target=square_data, args=(mydata, answer, square_sum)) #process begins from here p.start() #wait unless the process is completed p.join() # print an array of squared values for the main program print("Answer in main program: {}".format(answer[:])) # print the sum of squared values for the main program print("Sum of square values in main program: {}".format(square_sum.value))
輸出:
Answer in process p: [1, 4, 9]
Sum of squares in process p: 14
Answer in main program: [1, 4, 9]
Sum of squares in main program: 14
在上面的示例中,我們創(chuàng)建了一個數組并將三個整數傳遞給它。 我們打印了一個平方值數組,然后是進程 p 的平方值之和。
在此之后,我們再次為主程序打印一個平方值數組和平方值之和。
總結
可以通過多種方式來解釋使用 Python 的共享內存多處理。 因此,在本文中,我們解釋了多進程共享內存概念,即一個對象如何放置在共享內存空間并獨立運行。
除此之外,我們還了解到 Python 允許進程在不同進程之間共享數據。
到此這篇關于Python multiprocessing 共享對象的文章就介紹到這了,更多相關Python multiprocessing 共享內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python目錄操作之python遍歷文件夾后將結果存儲為xml
需求是獲取服務器某個目錄下的某些類型的文件,考慮到服務器即有Linux、又有Windows,所以寫了一個Python小程序來完成這項工作,大家參考使用吧2014-01-01