【发布时间】:2015-03-20 08:29:31
【问题描述】:
我对 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()
上面的程序说明了我的困惑 - 似乎 dict 自动在进程之间共享。我认为要获得这种行为,我必须使用多处理管理器。有人可以解释发生了什么吗?
【问题讨论】:
-
你在哪个操作系统上?
-
Ubuntu 14.04 64 位和 Python 2.7.6。