MPI并行计算

#centos7安装 mpi

yum install -y mpich*
vi mpitest1.c

#include <mpi.h>
#include <stdio.h>
#include <math.h>
int main(int argc,char** argv)
{
int myid,numproces;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Comm_size(MPI_COMM_WORLD,&numproces);
MPI_Get_processor_name(processor_name,&namelen);
fprintf(stdout,"hello world! Process %d of %d on %s\n",
myid,numproces,processor_name);
MPI_Finalize();

return 0;
}


mpicc mpitest1.c -o mpi1

mpirun -np 4 ./mpi1

 

 

vi mpitest2.c

#include <stdio.h>
#include <string.h>
#include <mpi.h>
#include <math.h>

int main(int argc,char** argv)
{
int numprocs, myid,source;
char message[100];
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
if (myid != 0) { //非0号进程发送消息
strcpy(message, "Hello World!");
MPI_Send(message, strlen(message) + 1, MPI_CHAR, 0, 99,
MPI_COMM_WORLD);
}
else { // myid == 0,即0号进程接收消息
for (source = 1; source < numprocs; source++) {
MPI_Recv(message, 100, MPI_CHAR, source, 99,
MPI_COMM_WORLD, &status);
printf("接收到第%d号进程发送的消息:%s\n", source, message);
}
}
MPI_Finalize();
return 0;
}

 

 

 

c mpi编译


mpicc mpitest2.c -o mpi2

mpirun -np 20 ./mpi2

posted @ 2021-05-14 11:05  小⑦  阅读(459)  评论(0)    收藏  举报