多处理的map函数忽略了我的全局变量的更新

时间:2014-04-04 11:45:16

标签: python global-variables multiprocessing

说我这样做:

import multiprocessing as mp

y = 10

def f(x) :
  return x + y

for i in xrange(2) :
  y = i
  pool = mp.Pool( processes = 2 )
  print pool.map( f, xrange(5) )

pool.close()
pool.join()

输出:

[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]

好的,这就是我的预期。但现在让我们在pool循环之外移动for的声明:

y = 10

def f(x) :
  return x + y

pool = mp.Pool( processes = 2 )

for i in xrange(2) :
  y = i
  print pool.map( f, xrange(5) )

输出:

[10, 11, 12, 13, 14]
[10, 11, 12, 13, 14]

忽略y的新值!发生了什么事?

1 个答案:

答案 0 :(得分:1)

来自https://docs.python.org/2/library/multiprocessing.html

  

在Unix上,子进程可以使用在a中创建的共享资源   使用全局资源的父进程。但是,最好通过   该对象作为子进程的构造函数的参数。

通过将命名空间中的所有数据从父命名空间复制到子命名空间,可以简化此功能(从父空间访问全局变量)。

所以,当你这样做时

y = i
pool = mp.Pool( processes = 2 )

子进程获取y的值为0(或者在循环的第二次运行中为1)。

同样,在代码中

y = 10
...
pool = mp.Pool( processes = 2 )
...
y = i

创建子进程时,它会获取父级环境的副本,其中y仍为10.此环境中y的任何后续更改都不会影响子进程。