#include"stdio.h"#include"mpi.h"#include<math.h>#include"stdlib.h"doublef(double);doublef(double x){return(4.0/(1.0+ x * x));}intmain(int argc,char** argv){int done =0, n, myid, numprocs, i;double PI25DT =3.141592653589792128462643;double mypi, pi, h, sum, x;double startwtime =0.0, endwtime;int nameelen;char processer_name[MPI_MAX_PROCESSOR_NAME];MPI_Init(&argc,&argv);MPI_Comm_rank(MPI_COMM_WORLD,&myid);MPI_Comm_size(MPI_COMM_WORLD,&numprocs);MPI_Get_processor_name(processer_name,&nameelen);fprintf(stdout,"process %d of %d on %s\n", myid, numprocs, processer_name);
n =0;if(myid ==0){printf("please give N=");scanf_s("%d",&n);
startwtime =MPI_Wtime();}MPI_Bcast(&n,1, MPI_INT,0, MPI_COMM_WORLD);
h =1.0/(double)n;
sum =0.0;for(i = myid +1; i <= n; i += numprocs){
x = h *((double)i -0.5);
sum +=f(x);
mypi = h * sum;MPI_Reduce(&mypi,&pi,1, MPI_DOUBLE, MPI_SUM,0, MPI_COMM_WORLD);if(myid ==0){printf("pi is approximately %.16f, Error is %.16f\n", pi,fabs(pi - PI25DT));
endwtime =MPI_Wtime();printf("wall clock time = %f\n", endwtime - startwtime);fflush(stdout);}}MPI_Finalize();return0;}
进程间阻塞通信
#include"stdio.h"#include"mpi.h"#include<string.h>#include<math.h>#include<cstdlib>#include"stdlib.h"intmain(int argc,char** argv){int N, K, myid;int sendid, dest;char* data =(char*)malloc(25*sizeof(char));int i =8, n;char* temp =(char*)malloc(2*sizeof(char));*temp ='i';strcpy_s(data,7,"hello!");
n =strlen(data);
data[n]=*temp;
data[n +1]=0;
K =(int)argv[1];
MPI_Status status;MPI_Init(&argc,&argv);MPI_Comm_size(MPI_COMM_WORLD,&N);MPI_Comm_rank(MPI_COMM_WORLD,&myid);
dest =(myid + K)% N;MPI_Send(data,1, MPI_INT, dest,100, MPI_COMM_WORLD);MPI_Recv(data,1, MPI_INT, MPI_ANY_SOURCE,100, MPI_COMM_WORLD,&status);printf("进程%d 发送消息%s 给进程%d ",(int)data[18], data, myid);MPI_Finalize();return0;}