2 Parallel Programming - 2026/2027
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.
31 int main(int argc
, char *argv
[])
36 int mpi_threads_support
;
38 // initialise MPI framework
39 MPI_Init_thread(&argc
, &argv
, MPI_THREAD_MULTIPLE
, &mpi_threads_support
);
41 MPI_Comm_rank(MPI_COMM_WORLD
, &rank
); // get process id
42 MPI_Comm_size(MPI_COMM_WORLD
, &processes
); // get number of processes
44 if (mpi_threads_support
< MPI_THREAD_MULTIPLE
&& rank
== 0)
45 warn("%s: warning: threads not fully supported\n", argv
[0]);
48 warn("%s: warning: there must be at least 2 processes\n", argv
[0]);
56 if (strcmp(argv
[arg
], "--quiet") == 0)
58 // silence debugging messages
61 else if (strcmp(argv
[arg
], "-r") == 0)
63 // re-seed random number generator
67 warn("%s: unknown option `%s'\n", argv
[0]);
72 // give all the processes a chance to start
73 MPI_Barrier(MPI_COMM_WORLD
);
77 printf("Starting basic algorithm\n");
79 // arguments for the basic and the control algorithms
80 thread_args_t threads_args
= { rank
, processes
, rank
== 0 };
82 // start basic algorithm thread
83 pthread_t basic_thread
;
85 if (pthread_create(&basic_thread
, NULL
, basic_algorithm
, &threads_args
) != 0)
87 perror("pthread_create (basic)");
92 // start control thread
93 pthread_t control_thread
;
95 if (pthread_create(&control_thread
, NULL
, detect_termination
, &threads_args
) != 0)
97 perror("pthread_create (control)");
102 // wait for control thread to end
103 pthread_join(control_thread
, NULL
);
105 // stop (terminated) basic algorithm thread
106 pthread_cancel(basic_thread
);
107 pthread_join(basic_thread
, NULL
);
113 printf("Terminating\n");