要求
使用mpi完成数列最大值的查找
代码
#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
int main(int argc, char **argv){
int rank, size;
int n,start,end;
int *arr;
int max,pmax,i;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &size);
if(rank == 0){
printf("plz input the length of your sequence: ");
scanf("%d", &n);
arr = (int*) malloc(sizeof(int) * n);
printf("then follows the sequence:\n");
getchar();
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for(i = 1; i < size; i++)
{
MPI_Send(&n, 1, MPI_INT, i, 99, comm);
}
for(i = 1; i < size; i++)
{
MPI_Send(arr, n, MPI_INT, i, 98, comm);
}
}
else{
MPI_Recv(&n, 1, MPI_INT, 0, 99, comm, &status);
arr = (int*) malloc(sizeof(int) * n);
MPI_Recv(arr, n, MPI_INT, 0, 98, comm, &status);
}
//calculate
if( n % size == 0){
start = n / size * rank;
end = n / size * (rank + 1) - 1;
}
else if(n > size)
{
start = (n / size) * rank;
if(rank == size - 1)
end = n - 1;
else
end = (n / size) * (rank + 1) - 1;
}
else{
printf("sequence len is too small\n");
MPI_Finalize();
return 0;
}
pmax = arr[start];
for(i = start; i <= end; i++){
if(arr[i] > pmax) pmax = arr[i];
}
if(rank != 0)
MPI_Send(&pmax, 1, MPI_INT, 0, 97, comm);
if(rank == 0){
max = pmax;
for(i = 1; i < size; i++){
MPI_Recv(&pmax, 1, MPI_INT, i, 97, comm, &status);
if(pmax > max) max = pmax;
}
printf("max is %d in process 0\n", max);
for(i = 1; i < size; i++){
MPI_Send(&max, 1, MPI_INT, i, 96, comm);
}
}
else{
MPI_Recv(&max, 1, MPI_INT, 0, 96, comm, &status);
printf("max is %d in process %d\n", max, rank);
}
MPI_Finalize();
return 0;
}