<p>答案其实很简单。您正在使用多处理模块,使用该模块可以启动几个不同的python进程。不同的进程有不同的地址空间,它们不共享内存,因此所有进程都会写入自己的本地字典副本。</p>
<p>使用多处理模块时,进行进程间通信的最简单方法是使用队列在从属进程和主进程之间进行通信。</p>
<pre><code>from multiprocessing import Process, Queue
def computeCopyNum(queue, val):
queue.put(val) # can also put a tuple of thread-id and value if we would like to
procs=list()
queue = Queue()
for i in range(1,3):
p = Process(target=computeCopyNum, args=(queue, i))
procs.append(p)
p.start()
for _ in procs:
val = queue.get()
# do whatever with val
for p in procs:
p.join()
</code></pre>
<p>如果每个从进程都可以生成多个输出值,那么让每个从进程向队列写入一个sentinel值以向主进程发出它已经完成的信号可能是明智的。然后代码可能看起来像:</p>
<pre><code>def slave(queue):
for i in range(128): # just for example
val = #some calculated result
queue.put(val)
queue.put(None) # add a sentinel value to tell the master we're done
queue = Queue()
# spawn 32 slave processes
num_procs = 32
procs = [Process(target=slave, args=(queue, )) for _ in range(num_procs)]
for proc in procs:
proc.start()
finished = 0
while finished < num_procs:
item = queue.get()
if item is None:
finished += 1
else:
# do something with item
for proc in procs:
proc.join()
</code></pre>
<p>您也可以使用管理器,如另一个答案所示。这种方法的问题是,进程地址空间之间可能会发生很多隐式内存复制,这很难解释。我总是喜欢使用显式队列。</p>