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.– jsbueno
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
@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?
– Vinícius Lara
yes - I think it will look better on another question, with the title on multi-processing
– jsbueno