#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int num_procs;
double x[MAX] = {1,3,56,24,54,54,35,245,23,52}; // Input array
int main(int argc, char *argv[])
{
int i,start, stop;
int myid;
double my_min; // Minimum
double others_min[100]; // Save minimum separately
double my_max; // Maximum
double others_max[100]; // Save maximum separately
MPI_Status st;
MPI_Request rq_min[100], rq_max[100]; // Status variables
MPI_Init(&argc,&argv); // Initialize
MPI_Comm_size(MPI_COMM_WORLD, &num_procs); // Get # processors
MPI_Comm_rank(MPI_COMM_WORLD, &myid); // Get my rank (id)
/* --------------------------------------
Find the min. among my numbers
-------------------------------------- */
int n = MAX/num_procs;
start = myid * n; //某并发进程子任务的数组起始位置
if ( myid != (num_procs-1) ) //最后一个进程不一定能分到n个元素
{
stop = start + n;
}
else
{
stop = MAX;
}
my_min = x[start]; //假定起始位置为最小值
for (i = start+1; i < stop; i = i + 1 )
{
if ( x[i] < my_min )
my_min = x[i];
}
if ( myid == 0 )
{
/* -------------------------------------
Get the min from others and compare
------------------------------------- */
for (i = 1; i < num_procs; i++)
{
MPI_Irecv(&others_min[i], 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &rq_min[i]);
}
}
else
{
MPI_Isend(&my_min, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&rq_min[0]);
}
/* --------------------------------------
Now find the max. among my numbers
-------------------------------------- */
my_max = x[start];
for (i = start+1; i < stop; i = i + 1 )
{
if ( x[i] > my_max )
my_max = x[i];
}
if ( myid == 0 )
{
/* -------------------------------------
Get the max from others and compare
------------------------------------- */
for (i = 1; i < num_procs; i++)
{
MPI_Irecv(&others_max[i], 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &rq_max[i]);
}
}
else
{
MPI_Isend(&my_max, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&rq_max[0]);
}
/* --------------------------------------
Now synchronize to compute results
-------------------------------------- */
if ( myid == 0 )
{
for ( i = 1; i < num_procs; i++)
{
MPI_Wait( &rq_min[i], &st );
if ( others_min[i] < my_min )
my_min = others_min[i];
}
for ( i = 1; i < num_procs; i++)
{
MPI_Wait( &rq_max[i], &st );
if ( others_max[i] > my_max )
my_max = others_max[i];
}
printf("min = %f\n",my_min);
printf("max = %f\n",my_max);
}
else
{ // The other processes must wait until their messages
// has been received before exiting !!!
MPI_Wait( &rq_min[0], &st );
MPI_Wait( &rq_max[0], &st );
}
MPI_Finalize();
}