問題描述
from multiprocessing import Process
# c is a container
p = Process(target = f, args = (c,))
p.start()
我假設 c
的深拷貝被傳遞給函數 f
因為淺拷貝在新進程的情況下沒有意義(新進程不可以訪問來自調用進程的數據).
I assume a deep copy of c
is passed to function f
because shallow copy would make no sense in the case of a new process (the new process doesn't have access to the data from the calling process).
但是這個深拷貝是如何定義的呢?copy 中有一整套 注釋集.deepcopy()
文檔,所有這些注釋是否也適用于這里?multiprocessing
文檔什么也沒說...
But how is this deep copy defined? There is a whole set of notes in the copy.deepcopy()
documentation, do all these notes apply here as well? The multiprocessing
documentation says nothing...
推薦答案
當你創建一個 Process
實例時,Python 會在底層發出一個 fork()
.這會創建一個子進程,其內存空間是其父進程的精確副本——因此在 fork 時存在的所有內容都會被復制.
When you create a Process
instance, under the hood Python issues a fork()
. This creates a child process whose memory space is an exact copy of its parent -- so everything existing at the time of the fork is copied.
在 Linux 上,這是通過寫時復制"來提高效率的.來自 fork 手冊頁:
On Linux this is made efficient through "copy-on-write". From the fork man page:
fork() 創建一個子進程僅與父進程不同在它的 PID 和 PPID 中,事實上資源利用率設置為0. 文件鎖和掛起信號不被繼承.
fork() creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.
Linux下實現fork()使用寫時復制頁面,所以唯一的它招致的懲罰是時間和復制所需的內存父的頁表,并創建一個孩子的獨特任務結構.
Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
這篇關于python多處理參數:深拷貝?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!