]> vgcfreebox.myrthtech.pt Git - ue-pp-terminationdetectionalgorithm.git/blob - util.c
f7fdbfaa401399985412734514a69e62d496e811
[ue-pp-terminationdetectionalgorithm.git] / util.c
1 /*
2 Parallel Programming - 2026/2027
3
4 Utility functions
5 */
6
7 #include <stdio.h>
8 #include <stdarg.h>
9 #include <stdlib.h>
10 #include <time.h>
11
12
13 // controls the output of debugging messages, set to 1 to have no
14 // messages
15 int QUIET = 0;
16
17
18 // returns a random integer in [A,B]
19 int rand_ab(int a, int b)
20 {
21 return a + rand() % (b - a + 1);
22 }
23
24 // sleep between MIN and MAX ms
25 void rand_sleep(int min, int max)
26 {
27 int ms = rand_ab(min, max);
28 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 };
29
30 nanosleep(&ts, NULL);
31 }
32
33 // output a debugging message to stderr
34 void trace(char *format, ...)
35 {
36 va_list args;
37
38 if (QUIET)
39 return;
40
41 va_start (args, format);
42 vfprintf(stderr, format, args);
43 va_end (args);
44 }
45
46 // unconditionally output a message to stderr
47 void warn(char *format, ...)
48 {
49 va_list args;
50
51 va_start (args, format);
52 vfprintf(stderr, format, args);
53 va_end (args);
54 }
55
56 /*
57 Evaluates Rule C & D of Dijkstra-Scholten. Caller must already hold state_mutex!
58 */
59 static void try_resolve_tree(int my_id)
60 {
61 if (state == PASSIVE_STATE && deficit == 0)
62 {
63 if (is_initiator) {
64 // Root is passive and deficit is 0 -> Global Termination!
65 return;
66 }
67
68 if (parent != -1)
69 {
70 control_message_t sig = {0};
71 // Send acknowledgment signal up the tree to our parent
72 MPI_Send(&sig, sizeof(control_message_t), MPI_BYTE, parent,
73 CONTROL_SIGNAL, MPI_COMM_WORLD);
74
75 trace("%d: [CONTROL] Sent tree-signal to parent %d\n", my_id, parent);
76 parent = -1; // Detach from tree
77
78 }
79 }
80 }