| 1 | /* An example shows the misusage of MPI collective routines. */
|
|---|
| 2 | #include<mpi.h>
|
|---|
| 3 | #include<stdio.h>
|
|---|
| 4 |
|
|---|
| 5 | int main(int argc, char* argv[]){
|
|---|
| 6 | int rank;
|
|---|
| 7 | int procs;
|
|---|
| 8 | int localsum, sum;
|
|---|
| 9 |
|
|---|
| 10 | MPI_Init(&argc,&argv);
|
|---|
| 11 | MPI_Comm_size(MPI_COMM_WORLD, &procs);
|
|---|
| 12 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 13 |
|
|---|
| 14 | localsum = 0;
|
|---|
| 15 | for(int i=0; i<=rank; i++){
|
|---|
| 16 | localsum += i;
|
|---|
| 17 | }
|
|---|
| 18 | printf("process %d has local sum of %d\n", rank, localsum);
|
|---|
| 19 | #ifdef ORDER
|
|---|
| 20 | if(rank%2){
|
|---|
| 21 | printf("process %d enters barrier\n", rank);
|
|---|
| 22 | MPI_Barrier(MPI_COMM_WORLD);
|
|---|
| 23 | printf("process %d exits barrier\n", rank);
|
|---|
| 24 | MPI_Reduce(&localsum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 25 | }else{
|
|---|
| 26 | MPI_Reduce(&localsum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 27 | printf("process %d enters barrier\n", rank);
|
|---|
| 28 | MPI_Barrier(MPI_COMM_WORLD);
|
|---|
| 29 | printf("process %d exits barrier\n", rank);
|
|---|
| 30 | }
|
|---|
| 31 | #else
|
|---|
| 32 | printf("process %d enters barrier\n", rank);
|
|---|
| 33 | MPI_Barrier(MPI_COMM_WORLD);
|
|---|
| 34 | printf("process %d exits barrier\n", rank);
|
|---|
| 35 | MPI_Reduce(&localsum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 36 | #endif
|
|---|
| 37 | if(rank == 0)
|
|---|
| 38 | printf("total sum is %d\n", sum);
|
|---|
| 39 | MPI_Finalize();
|
|---|
| 40 | return 0;
|
|---|
| 41 | }
|
|---|