pythonoopmultiprocessingmulti-level

Instance Variables Are Not Shared Between Processes in Python


I have a big problem with Multi Processing. in this case I have a

1.Main Class in Main Process

2.Foo Class in Another Process

I Have To Change Some Variables Inside of Process2 With Main Process. How Can I Do That/???

class Main:
     def __init__(self):
          self.Foo_Instance = Foo()
          multiprocessing.Process(target=self.Foo_Instance.do_something).start()

     def Change_Foo(self):
          Foo_Instance.ImportantVar = True
    
class Foo:
     def __init__(self):
          self.ImportantVar = False

     def do_something(self):
          pass

Main_Instance = Main()
Main_Instance.Change_Foo()

Solution

  • Each process in general has its own memory that is inaccessible to any other process. If you want one process to be able to modify a variable that another process is using, then the simplest solution is to create this variable in shared memory. In the demo below we create such a variable using a multiprocessing.Value instance. To demonstrate that Main.Change_Foo can modify Foo's ImportantVar attribute, we have to give Foo.do_something a chance to print out its initial value before Main.Change_Foo modifies it. Likewise, Foo.do_something needs to wait for Main.Change_Foo to change the value before it prints out the updated value. To accomplish this we use two 'multiprocessing.Event' instances:

    import multiprocessing
    import ctypes
    import time
    
    class Main:
        def __init__(self):
            self.Foo_Instance = Foo()
            multiprocessing.Process(target=self.Foo_Instance.do_something).start()
    
        def Change_Foo(self):
            # Wait for Foo.do_something to have printed out its initial value:
            self.Foo_Instance.initial_print_event.wait()
    
            # Modify the attribute (add missing self):
            self.Foo_Instance.ImportantVar.value = True
    
            # Show that we have modified the attribute:
            self.Foo_Instance.changed_event.set()
    
    
    class Foo:
        def __init__(self):
            self.ImportantVar = multiprocessing.Value(ctypes.c_bool, False, lock=False)
            self.initial_print_event = multiprocessing.Event()
            self.changed_event = multiprocessing.Event()
    
        def do_something(self):
            print('do_something before:', self.ImportantVar.value)
            # Show that we have completed printing our initial value:
            self.initial_print_event.set()
    
            # Now wait for Main.Change_Foo to have changed our variable:
            self.changed_event.wait()
    
            print('do_something after:', self.ImportantVar.value)
    
    
    # Required for Windows:
    if __name__ == '__main__':
        Main_Instance = Main()
        Main_Instance.Change_Foo()
    

    Prints:

    do_something before: False
    do_something after: True