numpy的ndarray在被multiprocessing调用的函数中作用是否有所不同?以下是一个例子:
使用Python的multiprocessing模块,我像这样调用一个函数:
for core in range(cores):
#target could be f() or g()
proc = mp.Process(target=f, args=(core))
jobs.append(proc)
for job in jobs:
job.start()
for job in jobs:
job.join()
def f(core):
x = 0
x += random.randint(0,10)
print x
def g(core):
#Assume an array with 4 columns and n rows
local = np.copy(globalshared_array[:,core])
shuffled = np.random.permutation(local)
调用 f(core)
函数时,变量 x
是进程局部的,即它打印的随机整数与预期不同。这些整数不超过 10,表明在每个进程中 x=0
。这是否正确?
调用 g(core)
函数并对数组的副本进行置换操作会返回 4 个完全相同的“洗牌”数组。这似乎表明工作副本不是子进程局部的。这是否正确?如果是,除了使用共享内存空间外,当需要从共享内存空间填充 ndarray 时,是否有可能将其设为子进程局部?
编辑:
将一个随机整数添加到 g(core)
函数中似乎产生了预期的效果。数组显示了不同的值。在 permutation
中发生了某些随机排序列(每个子进程都是局部的)的情况...有什么想法吗?
def g(core):
#Assume an array with 4 columns and n rows
local = np.copy(globalshared_array[:,core])
local += random.randint(0,10)
编辑 II:np.random.shuffle
也表现出相同的行为。数组的内容正在洗牌,但在每个核心上都洗牌到相同的值。
np.random.RandomState
这样的函数。 - sebergnp.random.random_integer
,但是返回的数组在所有进程中都是相同的。你是否引用了np.random.mtrand.RandomState
?因此,为每个子进程实例化一个随机类,因为它们可能会实例化一个类或互相覆盖。 - Jzl5325