Home >Backend Development >Python Tutorial >Instance variables are not shared between processes in Python
I'm having a big problem with multiprocessing. In this case I have a
1. Main class in the main process
2. Class foo in another process
I have to change some variables inside process2 using the main process. How can I do this/? ? ?
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()
Each process usually has its own memory that cannot be accessed by any other process. If you want one process to be able to modify a variable that is being used by another process, the simplest solution is to create the variable in shared memory. In the following demonstration, we use the multiprocessing.value
一个> instance. To prove that main.change_foo
can modify the importantvar
attribute of foo
, we must give foo before
main.change_foo modifies it .do_something
An opportunity to print out its initial value. Likewise, foo.do_something
needs to wait for main.change_foo
to change the value before printing out the updated value. To achieve 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()
Print:
do_something before: False do_something after: True
The above is the detailed content of Instance variables are not shared between processes in Python. For more information, please follow other related articles on the PHP Chinese website!