1
#include <mpi.h>
#include <stdio.h>
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
printf("Hello World!\n");
MPI_Finalize();
return 0;
}
2
include <stdio.h>
#include <mpi.h>
int main(int argc, char **argv)
{
int numprocs;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
printf("Hello World! The number of processes is %d\n",numprocs);
MPI_Finalize();
return 0;
}
int MPI_Comm_size(MPI_Comm comm, int *rank)
获取指定通信域的进程个数
3
#include <stdio.h>
#include <mpi.h>
int main(int argc, char **argv)
{
int myid, numprocs;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
//your code here
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
//end of your code
printf("Hello World!I'm rank %d of %d\n", myid, numprocs);
MPI_Finalize();
return 0;
}
int MPI_Comm_rank(MPI_Comm comm, int *rank)
输出当前进程的id,判断具体哪个进程完成了对应的任务
4
#include <stdio.h>
#include <mpi.h>
int main(int argc, char **argv)
{
int myid, numprocs, source;
MPI_Status status;
char message[100];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
if(myid != 0) {
strcpy(message, "hello world!");
//your code here
MPI_Send(message, strlen(message)+1, MPI_CHAR, 0, 99, MPI_COMM_WORLD);
//end of your code
}
else { //myid == 0
for(source=1; source<numprocs; source++) {
//your code here
MPI_Recv(message, 100, MPI_CHAR, source, 99, MPI_COMM_WORLD, &status);
//end of your code
printf("%s\n", message);
}
}
MPI_Finalize();
return 0;
}
int MPI_Send(void* msg_buf_p, int msg_size, MPI_Datatype msg_type, int dest, int tag, MPI_Comm communicator)
int MPI_Recv(void* msg_buf_p, int buf_size, MPI_Datatype msg_type, int source, int tag, MPI_Comm communicator, MPI_Status *status_p)
最基本发送/接收函数
5
#include <stdio.h>
#include <mpi.h>
int main(int argc, char **argv)
{
int myid, numprocs;
double local_num = 3.0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
double global_num;
//your code here
MPI_Reduce(&local_num, &global_num, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
//end of your code
if(myid == 0) {
printf("Total sum = %f, avg = %f\n", global_num, global_num / numprocs);
}
MPI_Finalize();
return 0;
}
int MPI_Reduce(void * input_data_p, void * output_data_p, int count, MPI_Datatype datatype, MPI_Op operator, int dest_process, MPI_Comm comm)
规约(reduce)
对于数据做同一种操作,并将结果返回到指定的进程中,这个过程称为集合通信。例如,将数据分散到各个进程中,先在各个进程内进行求和,再在全局完成求和-平均这个操作,这个过程是一个规约的过程。