I want to run several class instances in parallel and update the instance attributes using Redis. On each class instance, I run a thread in the background to listen to redis for changes. When I run set value 9 in redis, the thread detects the change, but the self.value attribute is not updated.
import time
import threading
import redis
class Foo:
def __init__(self, name: str):
self.name = name
self.redis_client = redis.Redis(host="localhost", port=6379)
self.value = 5
self.update_thread = threading.Thread(target=self.update, daemon=True)
self.update_thread.start()
def update(self):
while True:
new_value = int(self.redis_client.get("value"))
if new_value != self.value:
print("new value detected {}".format(new_value))
self.value = new_value
time.sleep(2)
def run(self):
while True:
print("{}: Value: {}".format(self.name, self.value))
time.sleep(2)
if __name__ == "__main__":
import multiprocessing
foo1 = Foo(name="foo1")
foo2 = Foo(name="foo2")
process1 = multiprocessing.Process(target=foo1.run)
process2 = multiprocessing.Process(target=foo2.run)
process1.start()
process2.start()
console output:
foo1: Value: 5
foo2: Value: 5
new value detected 9
new value detected 9
foo1: Value: 5
foo2: Value: 5
When I research the subject, I come across the information that "each process has its own memory space". But since I do not share data between processes in this case, I cannot understand why the data in the object instances cannot be preserved.