1

I have a function func1() inside which I want to do a parallel job using multi-threading. I am defining another function inside that function called func_thread() to access some local variables and avoid passing them to the thread function. However, for all those variables that are read-only, I do not have any problem. But, for the output value (x here which all threads are adding some value to x) I have trouble.

In this case I receive x referenced before assignment error.

def func1():
    lc = threading.Lock()
    x = np.zeros((100,100))
    def func_thread():
        lc.acquire()
        x = x + np.random.random((100,100))
        lc.release()

And in this case, I receive global variable x is not defined error!

def func1():
    x = np.zeros((100,100))
    def func_thread():
        global x
        x = x + np.random.random((100,100))
aminrd
  • 4,300
  • 4
  • 23
  • 45
  • 2
    Just call `func_thread` with `x`, won't you? – Jan Oct 01 '20 at 18:21
  • 1
    You want `nonlocal`, not `global`. It's explained [here](https://stackoverflow.com/questions/1261875/python-nonlocal-statement). Not sure if that counts as a duplicate though. – Carcigenicate Oct 01 '20 at 18:22
  • Declare both x as global,or the inner one as nonlocal. – MisterMiyagi Oct 01 '20 at 18:22
  • @Carcigenicate `nonlocal` worked, thanks. Please write it as an answer so that I can accept it. The link you sent was more general than my question but covers my answer as well. – aminrd Oct 01 '20 at 18:30
  • Please be aware that neither `a += b` nor `a = a + b` are atomic. They are not threadsafe even with the Gil, and introduce a subtle race condition. – MisterMiyagi Oct 01 '20 at 18:32
  • @MisterMiyagi Yes, I am using thread locks – aminrd Oct 01 '20 at 18:33
  • @aminrd Your question has been closed, so I'm unable to answer it. If anyone has a similar question as you though, the links here should help them (although I think the chosen dupe, while a good read, is a little broad). – Carcigenicate Oct 01 '20 at 18:33

0 Answers0