問題描述
我在這個網站的某個地方找到了以下示例:
I found the following example on this website somewhere:
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
上面的代碼工作正常,但是如果我想向共享數組添加一個數組,比如 shared_array += some_other_array (而不是上面的 shared_array[i,;] = i)我得到了
The above code works fine, but if I want to add an array to the shared array, something like shared_array += some_other_array (instead of the above shared_array[i,;] = i) I get
賦值前引用的局部變量shared_array"
local variable 'shared_array' referenced before assignment
任何想法為什么我不能這樣做?
Any ideas why I cannot do that?
推薦答案
如果一個變量被賦值給函數中的任何地方,它就會被視為一個局部變量.shared_array += some_other_array
等價于 shared_array = shared_array + some_other_array
.因此 shared_array
被視為局部變量,當您嘗試在賦值右側使用它時,該變量并不存在.
If a variable is assigned to anywhere in a function, it is treated as a local variable. shared_array += some_other_array
is equivalent to shared_array = shared_array + some_other_array
. Thus shared_array
is treated as a local variable, which does not exist at the time you try to use it on the right-hand side of the assignment.
如果你想使用全局 shared_array
變量,你需要通過在你的函數中放置一個 global shared_array
來顯式地將它標記為全局變量.
If you want to use the global shared_array
variable, you need to explicitly mark it as global by putting a global shared_array
in your function.
您沒有看到 shared_array[i,:] = i
錯誤的原因是它沒有分配給變量 shared_array
.相反,它改變了該對象,分配給它的一部分.在 Python 中,分配給一個裸名(例如,shared_array = ...
)與任何其他類型的分配(例如,shared_array[...] = ...
),盡管它們看起來很相似.
The reason you don't see the error with shared_array[i,:] = i
is that this does not assign to the variable shared_array
. Rather, it mutates that object, assigning to a slice of it. In Python, assigning to a bare name (e.g., shared_array = ...
) is very different from any other kind of assignment (e.g., shared_array[...] = ...
), even though they look similar.
請注意,順便說一下,該錯誤與多處理無關.
Note, incidentally, that the error has nothing to do with multiprocessing.
這篇關于多處理:在某些情況下,在賦值之前引用變量,但在其他情況下不引用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!