]> vgcfreebox.myrthtech.pt Git - ue-pp-terminationdetectionalgorithm.git/blob - termination.c
not a skeleton anymore
[ue-pp-terminationdetectionalgorithm.git] / termination.c
1 /*
2 Parallel Programming - 2026/2027
3
4 The main program
5 */
6
7 #include <mpi.h>
8 #include <pthread.h>
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <string.h>
14
15 #include "global.h"
16 #include "basic.h"
17 #include "control.h"
18 #include "util.h"
19
20 /*
21 Main program:
22
23 - Initialise the MPI environment.
24 - Process command line arguments.
25 - Start the basic algorithm thread.
26 - Start the control algorithm (termination detection) thread.
27 - Wait for the control algorithm to terminate, signalling that the
28 terminatation of the basic algorithm has been detected.
29 - Cancel the basic algorithm thread.
30 */
31 int main(int argc, char *argv[])
32 {
33 // process data
34 int rank, processes;
35
36 int mpi_threads_support;
37
38 // initialise MPI framework
39 MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &mpi_threads_support);
40
41 MPI_Comm_rank(MPI_COMM_WORLD, &rank); // get process id
42 MPI_Comm_size(MPI_COMM_WORLD, &processes); // get number of processes
43
44 if (mpi_threads_support < MPI_THREAD_MULTIPLE && rank == 0)
45 warn("%s: warning: threads not fully supported\n", argv[0]);
46
47 if (processes < 2)
48 warn("%s: warning: there must be at least 2 processes\n", argv[0]);
49
50 // parse arguments
51 int arg = 1;
52
53 while (arg < argc)
54 {
55 // parse one argument
56 if (strcmp(argv[arg], "--quiet") == 0)
57 {
58 // silence debugging messages
59 QUIET = 1;
60 }
61 else if (strcmp(argv[arg], "-r") == 0)
62 {
63 // re-seed random number generator
64 srand(time(0));
65 }
66 else
67 warn("%s: unknown option `%s'\n", argv[0]);
68
69 arg++;
70 }
71
72 // give all the processes a chance to start
73 MPI_Barrier(MPI_COMM_WORLD);
74
75 // the program
76 if (rank == 0)
77 printf("Starting basic algorithm\n");
78
79 // arguments for the basic and the control algorithms
80 thread_args_t threads_args = { rank, processes, rank == 0 };
81
82 // start basic algorithm thread
83 pthread_t basic_thread;
84
85 if (pthread_create(&basic_thread, NULL, basic_algorithm, &threads_args) != 0)
86 {
87 perror("pthread_create (basic)");
88
89 return 1;
90 }
91
92 // start control thread
93 pthread_t control_thread;
94
95 if (pthread_create(&control_thread, NULL, detect_termination, &threads_args) != 0)
96 {
97 perror("pthread_create (control)");
98
99 return 2;
100 }
101
102 // wait for control thread to end
103 pthread_join(control_thread, NULL);
104
105 // stop (terminated) basic algorithm thread
106 pthread_cancel(basic_thread);
107 pthread_join(basic_thread, NULL);
108
109 // wrap up
110 MPI_Finalize();
111
112 if (rank == 0)
113 printf("Terminating\n");
114
115 return 0;
116 }