Question on how shared memory works in Python's multi programming library

57 views Asked by At

I'm sure this has been answered before but I'd love to understand why this is occurring. My guess is its either something to do with Python's pass-by-object-reference attribute or something with shared memory.

Why when I dynamically change the self.size variable in ThreadSafeInt does it not update the copy owned by all other threads?

Output:

Value = 10
Value = 10
Value = 20
Done!

main.py

def change(num):
     num.setNum(20)

if __name__ == "__main__": 
     import sys
     num = ThreadSafeInt.ThreadSafeInt()
     num.setNum(10)
     print("Value = " + str(num.get()))
     #Changing value in different thread
     p3 = multiprocessing.Process(target=change, args=(num,)) 
     p3.start()
     p3.join()
     print("Value = " + str(num.get()))
     #Changing the value in same thread
     num.setNum(20)
     print("Value = " + str(num.get()))
     print("Done!")

ThreadSafeInt.py

import multiprocessing

class ThreadSafeInt:
     def __init__(self):
          self.size = multiprocessing.Value('i', 0)
          self.lock = multiprocessing.RLock()

     def get(self):
          with self.lock:
               return self.size.value
     def setNum(self, num):
          with self.lock:
               self.size = multiprocessing.Value('i', num)
1

There are 1 answers

0
toti08 On BEST ANSWER

In the setNum function when you set your new value you're defining a new Value object, so you're not modifying the existing one. If you change your code to:

class ThreadSafeInt:
     def __init__(self):
          self.size = multiprocessing.Value('i', 0)
          self.lock = multiprocessing.RLock()

     def get(self):
          with self.lock:
               return self.size.value
     def setNum(self, num):
          with self.lock:
               self.size.value = num   <--- change this line

it will work.

Output:
Value = 10
Value = 20
Value = 20
Done!