为什么 multiprocessing 模块产生的进程不复制内存?
Why do processes spawned by the multiprocessing module not duplicate memory?
我对 python 多处理的印象是,当您使用 multiprocessing.Process()
创建新进程时,它会在内存中创建当前程序的完整副本并从那里继续工作。考虑到这一点,我对以下脚本的行为感到困惑。
警告:此脚本将分配大量内存! 运行慎用!
import multiprocessing
import numpy as np
from time import sleep
#Declare a dictionary globally
bigDict = {}
def sharedMemory():
#Using numpy, store 1GB of random data
for i in xrange(1000):
bigDict[i] = np.random.random((125000))
bigDict[0] = "Known information"
#In System Monitor, 1GB of memory is being used
sleep(5)
#Start 4 processes - each should get a copy of the 1GB dict
for _ in xrange(4):
p = multiprocessing.Process(target=workerProcess)
p.start()
print "Done"
def workerProcess():
#Sleep - only 1GB of memory is being used, not the expected 4GB
sleep(5)
#Each process has access to the dictionary, even though the memory is shared
print multiprocessing.current_process().pid,bigDict[0]
if __name__ == "__main__":
sharedMemory()
上面的程序说明了我的困惑——似乎字典自动在进程之间共享。我想得到我必须使用多处理管理器的行为。谁能解释一下这是怎么回事?
在Linux,分叉一个进程不会导致内存立即被占用两倍。相反,新进程的页面 table 将被设置为指向与旧进程相同的物理内存,并且只有当其中一个进程尝试写入其中一个页面时,它们才实际获得已复制(写入时复制,COW)。结果是两个进程似乎都有单独的内存,但只有在其中一个进程实际接触到内存后才会分配物理内存。
我对 python 多处理的印象是,当您使用 multiprocessing.Process()
创建新进程时,它会在内存中创建当前程序的完整副本并从那里继续工作。考虑到这一点,我对以下脚本的行为感到困惑。
警告:此脚本将分配大量内存! 运行慎用!
import multiprocessing
import numpy as np
from time import sleep
#Declare a dictionary globally
bigDict = {}
def sharedMemory():
#Using numpy, store 1GB of random data
for i in xrange(1000):
bigDict[i] = np.random.random((125000))
bigDict[0] = "Known information"
#In System Monitor, 1GB of memory is being used
sleep(5)
#Start 4 processes - each should get a copy of the 1GB dict
for _ in xrange(4):
p = multiprocessing.Process(target=workerProcess)
p.start()
print "Done"
def workerProcess():
#Sleep - only 1GB of memory is being used, not the expected 4GB
sleep(5)
#Each process has access to the dictionary, even though the memory is shared
print multiprocessing.current_process().pid,bigDict[0]
if __name__ == "__main__":
sharedMemory()
上面的程序说明了我的困惑——似乎字典自动在进程之间共享。我想得到我必须使用多处理管理器的行为。谁能解释一下这是怎么回事?
在Linux,分叉一个进程不会导致内存立即被占用两倍。相反,新进程的页面 table 将被设置为指向与旧进程相同的物理内存,并且只有当其中一个进程尝试写入其中一个页面时,它们才实际获得已复制(写入时复制,COW)。结果是两个进程似乎都有单独的内存,但只有在其中一个进程实际接触到内存后才会分配物理内存。