-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
106 lines (81 loc) · 2.93 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import threading
from Simulation import Simulation
from simulation_worker import SimulationWorker
from utils.logger import setup_logger
from utils.config_loader import ConfigLoader
import logging
log = logging.getLogger(__name__)
class App:
def __init__(self):
self.threads = []
self.config = ConfigLoader.load()
self.max_threads = self.config.get("simulation").get("max_threads")
self.simulations = self.__create_simulations()
setup_logger(self.config.get("logger"))
def update(self):
self._start_n_simulations(n=self.max_threads, simulations=self.simulations)
self.iter_sims(simulations=self.simulations)
log.info("{} Simulation(s) left.".format(len(self.simulations)))
return self.simulations
def run(self):
while self.update():
pass
def __create_simulations(self):
result = []
for config in self.config["simulations"]:
result.append(self.__create_simulation(config=config))
log.info("All Simulations created.")
return result
@staticmethod
def __create_simulation(config):
"""
Creates a Simulation.
:param config: config with the Simulation parameters.
:return: a Simulation instance.
"""
log.info("Simulation created.")
return Simulation(config=config)
def iter_sims(self, simulations):
while simulations:
for i in range(len(self.threads)):
if not self.threads[i].is_alive():
self.threads[i].join()
self.threads.pop(i)
thread = self.__start_simulation(simulations.pop(0))
self.threads.append(thread)
def __wait_for_all_simulations(self):
"""
Waits until all threads are done.
:return: None
"""
for i in range(len(self.threads)):
thread = self.threads.pop()
thread.join()
log.info("Thread joined.")
def __start_all_simulations(self, simulations):
"""
Starts all threads.
:param simulations: a List of Simulations
:return: None
"""
for simulation in simulations:
thread = self.__start_simulation(simulation)
self.threads.append(thread)
def __start_simulation(self, simulation):
"""
Starts a Simulation in a Thread.
:param simulation: an instance of the Simulation class.
:return: a thread for later joining.
"""
thread = SimulationWorker(simulation, config=self.config)
thread.start()
log.info("Thread started.")
return thread
def _start_n_simulations(self, n, simulations):
for i in range(n):
if simulations:
thread = self.__start_simulation(simulations.pop(0))
self.threads.append(thread)
if __name__ == "__main__":
app = App()
app.run()