I am working on a project, where I have a main function, a class called simulator
and a class called vehicle
. In the main function I call: simulator.run()
which calls vehicle.run()
for all vehicles in simulator.vehicle_list[]
.
The vehicles have to calculate a trajectory, which is time-consuming process. These processes are independent of each other and I want the vehicle.run()
calculations to run on multiple CPU cores.
As starter I have created a simple project (with different class-names, than above, but intuitive enough I hope) but I cannot get it to work.
My code doesn't call self.calculate()
in the subclass. When I remove the if __name__ == '__main__':
statement from the master class, I get the error:
'multi_subclass' object has no attribute '_closed'
The three python files I have:
multi_main.py
from multi_class import multi_class
main_class = multi_class()
main_class.calculate()
#main_class.calculate2()
multi_class.py
from multi_subclass import multi_subclass
class multi_class():
def __init__(self):
print("I am multi_class")
subclass_list = []
for i in range(10):
subclass_list += [multi_subclass()]
self.subclass_list = subclass_list
def calculate(self):
if __name__ == '__main__':
processes = []
for i in range(10):
processes.append(self.subclass_list[i])
self.subclass_list[i].start()
[proc.join() for proc in processes]
multi_subclass.py
from multiprocessing import Process
class multi_subclass(Process):
def __init__(self):
print("I am multi_subclass")
def calculate(self):
print("Running massive calculations")
self.member_variable = "Finished with calculation"
def calculate2(self):
print("I also want to be paralellized but NOT together with calculate!")
def run(self):
self.calculate()