use*_*020 3 python multiprocessing python-2.7
我在这个网站上找到了以下示例:
import multiprocessing
import ctypes
import numpy as np
shared_array_base = multiprocessing.Array(ctypes.c_double, 10*10)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(10, 10)
# No copy was made
assert shared_array.base.base is shared_array_base.get_obj()
# Parallel processing
def my_func(i, def_param=shared_array):
shared_array[i,:] = i
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
pool.map(my_func, range(10))
print shared_array
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,但如果我想在共享数组中添加一个数组,比如shared_array + = some_other_array(而不是上面的shared_array [i,;] = i)我得到了
赋值前引用的局部变量'shared_array'
任何想法为什么我不能这样做?
如果将变量分配给函数中的任何位置,则将其视为局部变量. shared_array += some_other_array相当于shared_array = shared_array + some_other_array.因此shared_array被视为局部变量,在您尝试在赋值的右侧使用它时不存在.
如果要使用全局shared_array变量,则需要global shared_array在函数中添加一个显式标记为全局变量.
您没有看到错误的原因shared_array[i,:] = i是这不会分配给变量shared_array.相反,它会改变该对象,分配给它的一部分.在Python中,分配给一个裸名称(例如shared_array = ...)与任何其他类型的赋值(例如shared_array[...] = ...)非常不同,即使它们看起来相似.
顺便提一下,请注意该错误与多处理无关.