I have a piece of code that is constantly creating new instances of class Car. In doing so, class Car is creating a list of instances of itself so when I want to get the info of the current instances, I can easily do so, like in the below code:
from multiprocessing import Process
import time
class Car:
car_list = list()
def __init__(self, id, model):
self.id = id
self.model = model
Car.car_list.append(self)
@classmethod
def get_current_instances(cls):
return Car.car_list
class Interface:
def print_current_system(self):
while True:
print(len(Car.get_current_instances()))
time.sleep(1)
if __name__ == "__main__":
interface = Interface()
model = ["Toyota", "BMW"]
[Car(i, model[i]) for i in range(len(model))]
print_process = Process(target=interface.print_current_system)
print_process.start()
Car(2345, "Tesla")
print("from main process " + str(len(Car.get_current_instances())))
This code is simplified for the purpose of the question. However, the problem still remains the same. I am invoking a function print_current_system from a new process. This function is constantly looking at all the current instances of Car and prints the number of cars.
When I start this process, and then, later on, add some new instances of Car, these instances are hidden to the other child process while are perfectly visible to the main process. I am pretty sure I need to use something like Queue or Pipe. However, I am not sure how. This is the output of the above code:
2
from main process 3
2
2
2
2
2