简体   繁体   中英

How can I create functions which access variables that are created in the run function of a subclassed python Process

If I have a python class

from multiprocessing import Process

class A(Process):
    def run(self):
        self.var = "asdf"

    def pprint(self):
        print(self.var)

if __name__ == "__main__":
    foo = A()
    foo.start()
    foo.pprint()
    bar = A()
    bar.pprint()

I get the traceback error

Traceback (most recent call last):
  File "simple.py", line 13, in <module>
    foo.pprint()
  File "simple.py", line 8, in pprint
    print(self.var)
AttributeError: 'A' object has no attribute 'var'

Can I access instance variables that are defined within the run function, with other functions defined in the scope of the class?

from multiprocessing import Process

class A(Process):  
  def __init__(self, value):
    self.var = value  
  def run(self):
    self.var = "asdf"
  def pprint(self):
    print(self.var)


foo = A("asdf")
foo.start()
foo.pprint()
bar = A("qwerty")
bar.pprint()

The run() function is executed in another process and the variable is only created there while pprint() is executed in current process. You can eg use a Manager to get a dict to store data common for all processes or exchange data using pipes or queues (read the documentation about that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM