Home > Blockchain >  Python: Change class member in a thread
Python: Change class member in a thread

Time:03-23

I am currently trying to change member variables of a class via a separate thread. I want to access the changed variables from the main process, but it seems that a copy is always created that is no longer visible to the main thread. Do you have any ideas here? Many thanks in advance for your help. Example code:

class foo():
 def __init__(self):
     self.data = 0

 def test_f(self):
     for it in range(0,3):
         self.data = self.data   1
         time.sleep(1.0)
     print('thread terminated')
     print(self.data)

#This function is outside the class; Unfortunately, indentations do not work properly here right now

def run(m_foo):
 for it in range(0,10):
     m_foo.test_f(q)
     time.sleep(1.0)

if __name__ == '__main__':
 m_foo = foo()
 p = Process(target=run, args=(m_foo))
 p.start()     
stop_char = ""
while stop_char.lower() != "q":
    stop_char = input("Enter 'q' to quit\n")        
    print("Process data:")
    print(foo.data)
if p.is_alive():
   p.terminate()

Output: Process data: 0 .... thread terminated 21 thread terminated 24 thread terminated 27 thread terminated 30 ... Process data: 0

CodePudding user response:

The class multiprocessing.Process does not create a thread. It creates a completely new processing with its own memory space.

Use threading.Thread instead:
https://docs.python.org/3/library/threading.html#threading.Thread

  • Related