1.规约
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)
1 #include <stdio.h> 2 #include <mpi.h> 3 4 int main(int argc, char **argv) 5 { 6 int myid, numprocs; 7 double local_num = 3.0; 8 9 MPI_Init(&argc, &argv); 10 11 MPI_Comm_rank(MPI_COMM_WORLD, &myid); 12 MPI_Comm_size(MPI_COMM_WORLD, &numprocs); 13 14 double global_num; 15 16 //your code here 17 MPI_Reduce(&local_num, &global_num, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); 18 //end of your code 19 20 if(myid == 0) { 21 printf("Total sum = %f, avg = %f ", global_num, global_num / numprocs); 22 } 23 24 MPI_Finalize(); 25 return 0; 26 }
2.广播
int MPI_Bcast(void* buffer, int count, MPI_Datatype datatype, int source, MPI_Comm comm)
1 #include<stdio.h> 2 #include<mpi.h> 3 4 int main(int argc, char **argv) 5 { 6 int myid, numprocs; 7 int source = 0; 8 int array[5]={1,2,3,4,5}; 9 int i; 10 11 MPI_Init(&argc, &argv); 12 13 MPI_Comm_rank(MPI_COMM_WORLD, &myid); 14 MPI_Comm_size(MPI_COMM_WORLD, &numprocs); 15 16 if(myid == source) { 17 for(i = 1; i <= 5; i++) 18 array[i] = i; 19 } 20 21 //your code here 22 MPI_Bcast(array, 5, MPI_INT, source, MPI_COMM_WORLD); 23 //end of your code 24 25 if(myid != source) { 26 printf("In process %d, ", myid); 27 for(i = 0; i < 5; i++) 28 printf("arr[%d]=%d ", i, array[i]); 29 printf(" "); 30 } 31 32 MPI_Finalize(); 33 return 0; 34 }
来自:MPI编程实训学习(超算习堂)