MPI 学习
一、编译MPI
mpic++ test.cc -o test
二、启动MPI
mpiexec -np 10 ./test
三、几个例子
第一个进程向第二个发一个数,第二个进程向第三个进程发送一个数。。。依次传递
1 #include "mpi.h" 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <time.h> 5 #include <string.h> 6 #include <iostream> 7 #include <unistd.h> 8 9 10 using namespace std; 11 12 int main(int argc, char **argv) 13 { 14 int myid, numprocs, num; 15 16 MPI_Init(&argc, &argv); 17 MPI_Comm_rank(MPI_COMM_WORLD, &myid); 18 MPI_Comm_size(MPI_COMM_WORLD, &numprocs); 19 MPI_Status status; 20 21 if (numprocs < 2) { 22 printf("Processes must >= 2! \n"); 23 MPI_Abort(MPI_COMM_WORLD, 99); 24 } 25 26 do { 27 //master 28 if (myid == 0) { 29 cout << "please input a number" << endl; 30 cin >> num; 31 //send number 32 if (numprocs > 1) { 33 MPI_Send(&num, 1, MPI_INT, myid + 1, 0, MPI_COMM_WORLD); 34 cout << myid << " send " << num << " to " << myid + 1 << endl; 35 } 36 } 37 //slave 38 else { 39 MPI_Recv(&num, 1, MPI_INT, myid - 1, 0, MPI_COMM_WORLD, &status); 40 cout << myid << " receive " << num << " from " << myid - 1 << endl; 41 if (myid < numprocs - 1) { 42 MPI_Send(&num, 1, MPI_INT, myid + 1, 0, MPI_COMM_WORLD); 43 cout << myid << " send " << num << " to " << myid + 1 << endl; 44 } 45 } 46 MPI_Barrier(MPI_COMM_WORLD); // wait all pro finish 47 } while (num > 0); 48 49 MPI_Finalize(); 50 51 return 0; 52 }
收集(Gather) http://scc.ustc.edu.cn/zlsc/cxyy/200910/MPICH/mpi45.htm
http://scc.ustc.edu.cn/zlsc/cxyy/200910/MPICH