2 Parallel Programming - 2026/2027
4 Skeleton of an implementation of a termination detection algorithm
18 // the tag(s) of the control messages
19 #define CONTROL_SIGNAL 99 // --> must be distinct from BASIC_MESSAGE = 1
21 // type for control messages
26 // Node operational states
33 // Shared Local State (Protected by state_mutex)
34 static pthread_mutex_t state_mutex
= PTHREAD_MUTEX_INITIALIZER
;
35 static node_state_t state
= PASSIVE_STATE
;
36 static int parent
= -1; // -1 indicates null/no parent
37 static int deficit
= 0; // C_i counter
38 static bool is_initiator
= false;
42 Main loop of the termination detection algorithm.
44 When termination is detected, it must end (returning NULL or another
45 appropriate value), which signals the main thread that the basic
46 algorithm has terminated.
48 The arguments of the termination detection algorithm are the ID of
49 the process, the number of PROCESSES running the basic algorithm,
50 and whether the process is an initiator.
52 void *detect_termination(void *_args
){
53 thread_args_t
*args
= _args
;
55 int processes
= args
->processes
;
56 bool initiator
= args
->initiator
;
59 pthread_mutex_lock(&state_mutex
);
61 // CHECK GLOBAL TERMINATION CONDITION (only happens at root)
62 if (initiator
&& state
== PASSIVE_STATE
&& deficit
== 0)
64 trace("%d: [CONTROL] GLOBAL TERMINATION DETECTED!\n", id
);
65 pthread_mutex_unlock(&state_mutex
);
66 break; // Breaks loop, returns NULL, tells main() to shut down
69 pthread_mutex_unlock(&state_mutex
);
71 // Check network for incoming child signals (non-blocking with MPI_Iprobe)
74 MPI_Iprobe(MPI_ANY_SOURCE
, CONTROL_SIGNAL
, MPI_COMM_WORLD
, &flag
, &status
);
77 control_message_t sig
;
78 MPI_Recv(&sig
, sizeof(control_message_t
), MPI_BYTE
, status
.MPI_SOURCE
,
79 CONTROL_SIGNAL
, MPI_COMM_WORLD
, MPI_STATUS_IGNORE
);
81 pthread_mutex_lock(&state_mutex
);
83 trace("%d: [CONTROL] Got signal from %d (New Deficit: %d)\n",
84 id
, status
.MPI_SOURCE
, deficit
);
87 pthread_mutex_unlock(&state_mutex
);
90 // Sleep for 1 millisecond to prevent this while(true) loop
91 // from pinning the CPU core at 100% usage
100 Called at startup of the basic algorithm in process ID.
102 void control_basic_start_hook(int id
)
107 Called when the basic algorithm process ID becomes passive.
109 void control_become_passive_hook(int id
)
114 Called when the basic algorithm process ID becomes active.
116 void control_become_active_hook(int id
)
121 Called when the basic algorithm process ID sends a basic message to
124 void control_basic_send_hook(int id
, int peer
)
129 Called when the basic algorithm process ID receives a basic message
132 void control_basic_receive_hook(int id
, int peer
)