假设我这样做:
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 的新值被忽略了!怎么回事?
请您参考如下方法:
来自 https://docs.python.org/2/library/multiprocessing.html :
On Unix a child process can make use of a shared resource created in a parent process using a global resource. However, it is better to pass the object as an argument to the constructor for the child process.
此功能(从父空间访问全局变量)通过将命名空间中的所有数据从父命名空间复制到子命名空间来简单实现。
所以,当你这样做的时候
y = i
pool = mp.Pool( processes = 2 )
子进程获取值为 0 的 y(或 1,在循环的第二次运行中)。
同样,在代码中
y = 10
...
pool = mp.Pool( processes = 2 )
...
y = i
创建子进程时,它会获得父环境的副本,其中 y 仍为 10。以后在该环境中对 y 的任何更改都不会影响子进程。
