#C
Create the file mpi_sections.c
and copy in the following;
#include <mpi.h>
#include <stdio.h>
#include <unistd.h>
void times_table(int n)
{
int i, i_times_n, rank;
(MPI_COMM_WORLD, &rank);
MPI_Comm_rank
for (i=1; i<=n; ++i)
{
= i * n;
i_times_n ("Process %d says %d times %d equals %d.\n",
printf, i, n, i_times_n );
rank
(1);
sleep}
}
void countdown()
{
int i, rank;
(MPI_COMM_WORLD, &rank);
MPI_Comm_rank
for (i=10; i>=1; --i)
{
("Process %d says %d...\n", rank, i);
printf(1);
sleep}
("Process %d says \"Lift off!\"\n", rank);
printf}
void long_loop()
{
int i, rank;
double sum = 0;
(MPI_COMM_WORLD, &rank);
MPI_Comm_rank
for (i=1; i<=10; ++i)
{
+= (i*i);
sum (1);
sleep}
("Process %d says the sum of the long loop is %f\n",
printf, sum);
rank}
int main(int argc, char **argv)
{
int rank;
(&argc, &argv);
MPI_Init
(MPI_COMM_WORLD, &rank);
MPI_Comm_rank
if (rank == 0)
{
("This is the main process.\n");
printf(12);
times_table}
else if (rank == 1)
{
();
countdown}
else if (rank == 2)
{
();
long_loop}
else
{
("I am not needed...\n");
printf}
();
MPI_Finalize
return 0;
}
Note that we have included the header file unistd.h
to use the function sleep
, to add one second pauses (via sleep(1)
) within each function.
In this example we use the function MPI_Comm_rank(MPI_COMM_WORLD, int *rank)
. This function puts the rank of the calling process into the variable pointed to by rank
. This allows the if
block to be used to control which function is called by which process in the MPI process team. While it is possible to write the code within each block of the if
statement directly, the code is more readable if you write each section as a function (e.g. countdown
, long_loop
and times_table
) and just call the function from within each block.
You can compile this program using;
mpicc mpi_sections.c -o mpi_sections
This will produce the executable, mpi_sections
.