MPI并行计算——点对点通信(求数组的最大值)

要求

使用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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值