【MPI】并行求和
比较简单的并行求和 读入还是串行的 而且无法处理线程数无法整除数据总长度的情况
主要用到了MPI_Bcast MPI_Scatter MPI_Reduce
typedef long long __int64;
#include "mpi.h"
#include <cstdio>
#include <cmath>
using namespace std;
int main(int argc, char* argv[]){
int my_rank=0, comm_sz=0, local_int=0, total_int=0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
int *a,*local_a;
int n;
if(my_rank==0){
scanf("%d",&n);
}
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
local_a=new int[n/comm_sz];
if(my_rank==0){
a=new int[n];
for(int i=0;i<n;++i){
scanf("%d",&a[i]);
}
MPI_Scatter(a,n/comm_sz,MPI_INT,local_a,n/comm_sz,MPI_INT,0,MPI_COMM_WORLD);
delete[] a;
}
else{
MPI_Scatter(a,n/comm_sz,MPI_INT,local_a,n/comm_sz,MPI_INT,0,MPI_COMM_WORLD);
}
for(int i=0;i<n/comm_sz;++i){
local_int+=local_a[i];
}
delete[] local_a;
MPI_Reduce(&local_int,&total_int,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
if (my_rank == 0)
{
printf("%d个线程,每份长度为%d,结果为%d\n", comm_sz, n/comm_sz, total_int);
}
MPI_Finalize();
return 0;
}
——The Solution By AutSky_JadeK From UESTC
转载请注明出处:http://www.cnblogs.com/autsky-jadek/

浙公网安备 33010602011771号
