| [6546348] | 1 | /**
|
|---|
| 2 | * This is a simple program to demonstrate the correct usage of two MPI colletive operations,
|
|---|
| 3 | * i.e., they have to be executed in the same order for each process.
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | #include<mpi.h>
|
|---|
| 7 | #include<stdlib.h>
|
|---|
| 8 | #include<assert.h>
|
|---|
| 9 | #include<stdio.h>
|
|---|
| 10 |
|
|---|
| [8f2c865] | 11 | int main(int argc, char * argv[])
|
|---|
| [6546348] | 12 | {
|
|---|
| 13 | int rank;
|
|---|
| 14 | int procs;
|
|---|
| 15 | int* sendBuf;
|
|---|
| 16 | int* rcvBuf;
|
|---|
| 17 | int* sum;
|
|---|
| 18 |
|
|---|
| 19 | MPI_Init(&argc,&argv);
|
|---|
| 20 | MPI_Comm_size(MPI_COMM_WORLD, &procs);
|
|---|
| 21 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 22 |
|
|---|
| 23 | if (rank == 0) {
|
|---|
| 24 | sendBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 25 | sum = (int*)malloc(sizeof(int)*procs);
|
|---|
| 26 | for(int i=0; i < procs; i++){
|
|---|
| 27 | sendBuf[i] = i;
|
|---|
| 28 | sum[i] = 0;
|
|---|
| 29 | }
|
|---|
| 30 | }else{
|
|---|
| 31 | sum = (int*)malloc(sizeof(int));
|
|---|
| 32 | sendBuf = (int*)malloc(sizeof(int));
|
|---|
| 33 | }
|
|---|
| 34 | rcvBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 35 |
|
|---|
| 36 | MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 37 |
|
|---|
| 38 | *sendBuf = *rcvBuf;
|
|---|
| 39 |
|
|---|
| 40 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 41 |
|
|---|
| [8f2c865] | 42 | printf("Vector of process %d is: (", rank);
|
|---|
| [6546348] | 43 | for(int i=0; i<procs; i++){
|
|---|
| 44 | printf("%d", rcvBuf[i]);
|
|---|
| 45 | if(i != procs-1)
|
|---|
| 46 | printf(", ");
|
|---|
| 47 | assert(i == rcvBuf[i]);
|
|---|
| 48 | }
|
|---|
| 49 | printf(")\n");
|
|---|
| 50 |
|
|---|
| [8f2c865] | 51 | MPI_Bcast(sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| [6546348] | 52 |
|
|---|
| 53 | MPI_Reduce(rcvBuf, sum, procs, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 54 |
|
|---|
| 55 | if(rank == 0){
|
|---|
| 56 | printf("Vector sum is: (");
|
|---|
| 57 | for(int i=0; i<procs; i++){
|
|---|
| 58 | printf("%d", sum[i]);
|
|---|
| 59 | if(i != procs-1)
|
|---|
| 60 | printf(", ");
|
|---|
| 61 | assert(i*procs == sum[i]);
|
|---|
| 62 | }
|
|---|
| 63 | printf(")\n");
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 | free(sendBuf);
|
|---|
| 67 | free(rcvBuf);
|
|---|
| 68 | free(sum);
|
|---|
| [34f73ef] | 69 | MPI_Finalize();
|
|---|
| [6546348] | 70 | return 0;
|
|---|
| 71 | }
|
|---|