multiprocessing: variable being referenced before assignment in some cases but not others

后端 未结 1 1999
执笔经年
执笔经年 2020-12-21 07:07

I found the following example on this website somewhere:

import multiprocessing
import ctypes
import numpy as np

shared_array_base = multiprocessing.Array(c         


        
相关标签:
1条回答
  • 2020-12-21 07:33

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题