How to change parameters of a class within a thread

Asked

Viewed 113 times

1

I am initiating a class in the global scope, then I create a thread that alters a parameter of this class. After closing the thread I ask the class what parameter value I just changed, it tells me that it has not changed anything.

Why and how to solve this?

My code:

import multiprocessing 
import time

class Car:

    color = None

    def __init__(self):
        self.color = "green"

    def changeColor(self, color):
        self.color = color

    def getColor(self):
        return self.color

car1 = Car()

def carshop():
    car1.changeColor("red")
    print(car1.getColor())

th = multiprocessing.Process(target = carshop, args=())
th.start()

time.sleep(2)

print(car1.getColor())

Return of this code:

red
green

how this code should return:

red 
red
  • It also makes no sense to use getters and setters in Python the way you’re doing. Because you’re doing this in a multi-threading environment, you might want to write getters and setters that use a Lock to avoid race-conditions - but in this case, in Python, use a @property - no code that way there.

  • and I didn’t comment on the question, because the existing answer is correct: you’re using multiprocessing: it’s different from threading. If the above code was threaded, the object car1 would have been altered, and the same obj is visible on all threads. With multi-processing, when the worker process is created, all variables of the current process are cloned in the new process, and have independent life from there - only explicit inter-process communication (for example, with a multiprocessing.Queue)to pass data back and forth.

  • @jsbueno interesting your point, in fact the code I showed is just example for a larger problem that would not be interesting to post here, but I will follow your line. I can’t use threads but wanted to update this variable in the global scope, could do this with this communication queue?

  • yes - I think it will look better on another question, with the title on multi-processing

1 answer

2


You are using multiprocessing. The shortest and simplest answer is that processes do not share memory by default. Try to use threading instead.

import threading
import time

class Car:
    def __init__(self):
        self.color = "green"

    def changeColor(self, color):
        self.color = color

    def getColor(self):
        return self.color

car1 = Car()

def carshop():
    car1.changeColor("red")
    print(car1.getColor())

if __name__ == '__main__':
    th = threading.Thread(target=carshop)
    th.start()

    time.sleep(2)
    print(car1.getColor())
  • Is there any way to force him to share?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.