一、编译MPI
mpic++ test.cc -o test
二、启动MPI
mpiexec -np 10 ./test
三、几个例子
第一个进程向第二个发一个数,第二个进程向第三个进程发送一个数。。。依次传递
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <iostream>
#include <unistd.h> using namespace std; int main(int argc, char **argv)
{
int myid, numprocs, num; MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Status status; if (numprocs < ) {
printf("Processes must >= 2! \n");
MPI_Abort(MPI_COMM_WORLD, );
} do {
//master
if (myid == ) {
cout << "please input a number" << endl;
cin >> num;
//send number
if (numprocs > ) {
MPI_Send(&num, , MPI_INT, myid + , , MPI_COMM_WORLD);
cout << myid << " send " << num << " to " << myid + << endl;
}
}
//slave
else {
MPI_Recv(&num, , MPI_INT, myid - , , MPI_COMM_WORLD, &status);
cout << myid << " receive " << num << " from " << myid - << endl;
if (myid < numprocs - ) {
MPI_Send(&num, , MPI_INT, myid + , , MPI_COMM_WORLD);
cout << myid << " send " << num << " to " << myid + << endl;
}
}
MPI_Barrier(MPI_COMM_WORLD); // wait all pro finish
} while (num > ); MPI_Finalize(); return ;
}
收集(Gather) http://scc.ustc.edu.cn/zlsc/cxyy/200910/MPICH/mpi45.htm