-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
80 lines (63 loc) · 2.01 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
import os, threading
import multiprocessing
from Node import runNode
from Utils import *
import random
import time
queues_main_to_procs = []
queues_procs_to_main = []
procs = []
sudden_offs = set()
running = True
def randomTermination():
global N_OF_NODES, sudden_offs, e_end
while True:
if not running:
break
e_end.wait(timeout=TIME_SUDDEN_OFF_INTERVAL)
if not running:
break
rint = random.randint(0, N_OF_NODES-1)
while rint in sudden_offs:
rint = random.randint(0, N_OF_NODES-1)
sudden_offs.add(rint)
queues_main_to_procs[rint].put("off")
t_onner = threading.Thread(target=turnOn, args=(rint,))
t_onner.start()
print(f"Main : sends off to node {rint}")
def turnOn(_id):
e_end.wait(TIME_SUDDEN_OFF_DURATION)
print(f"Main : sends on to node {_id}")
queues_main_to_procs[_id].put("on")
sudden_offs.remove(_id)
def endSimulation():
global running
time.sleep(TIME_SIMULATION)
print("Main : Start an end :)")
e_end.set()
running = False
for queue in queues_main_to_procs:
queue.put("end")
if __name__ == "__main__":
for i in range(N_OF_NODES):
q1 = multiprocessing.Queue()
q2 = multiprocessing.Queue()
queues_main_to_procs.append(q1)
queues_procs_to_main.append(q2)
procs.append(multiprocessing.Process(target=runNode, args=(q1, q2, i, 'localhost', START_PORT + i)))
for item in procs:
item.start()
e_end = threading.Event()
e_end.clear()
t_randterminator = threading.Thread(target=randomTermination)
t_endSimulation = threading.Thread(target=endSimulation)
t_randterminator.setDaemon(False)
t_randterminator.start()
t_endSimulation.start()
for i in range(N_OF_NODES):
msg = queues_procs_to_main[i].get()
if msg == "done":
procs[i].terminate()
else:
print("Unknown message from proc " + str(i))
print("end of main proc")