| [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 |
|
|---|
| 11 | #define SIZE 5
|
|---|
| 12 |
|
|---|
| 13 | int main()
|
|---|
| 14 | {
|
|---|
| 15 | int argc;
|
|---|
| 16 | char** argv;
|
|---|
| 17 | int rank;
|
|---|
| 18 | int procs;
|
|---|
| 19 | int* sendBuf;
|
|---|
| 20 | int* rcvBuf;
|
|---|
| 21 | int* sum;
|
|---|
| 22 |
|
|---|
| 23 | MPI_Init(&argc,&argv);
|
|---|
| 24 | MPI_Comm_size(MPI_COMM_WORLD, &procs);
|
|---|
| 25 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 26 |
|
|---|
| 27 | if (rank == 0) {
|
|---|
| 28 | sendBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 29 | sum = (int*)malloc(sizeof(int)*procs);
|
|---|
| 30 | for(int i=0; i < procs; i++){
|
|---|
| 31 | sendBuf[i] = i;
|
|---|
| 32 | sum[i] = 0;
|
|---|
| 33 | }
|
|---|
| 34 | }else{
|
|---|
| 35 | sum = (int*)malloc(sizeof(int));
|
|---|
| 36 | sendBuf = (int*)malloc(sizeof(int));
|
|---|
| 37 | }
|
|---|
| 38 | rcvBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 39 |
|
|---|
| 40 | MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 41 |
|
|---|
| 42 | *sendBuf = *rcvBuf;
|
|---|
| 43 |
|
|---|
| 44 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 45 |
|
|---|
| 46 | printf("Vector process %d is: (", rank);
|
|---|
| 47 | for(int i=0; i<procs; i++){
|
|---|
| 48 | printf("%d", rcvBuf[i]);
|
|---|
| 49 | if(i != procs-1)
|
|---|
| 50 | printf(", ");
|
|---|
| 51 | assert(i == rcvBuf[i]);
|
|---|
| 52 | }
|
|---|
| 53 | printf(")\n");
|
|---|
| 54 |
|
|---|
| 55 | MPI_Scatter(sum, 1, MPI_INT, sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 56 |
|
|---|
| 57 | MPI_Reduce(rcvBuf, sum, procs, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 58 |
|
|---|
| 59 | if(rank == 0){
|
|---|
| 60 | printf("Vector sum is: (");
|
|---|
| 61 | for(int i=0; i<procs; i++){
|
|---|
| 62 | printf("%d", sum[i]);
|
|---|
| 63 | if(i != procs-1)
|
|---|
| 64 | printf(", ");
|
|---|
| 65 | assert(i*procs == sum[i]);
|
|---|
| 66 | }
|
|---|
| 67 | printf(")\n");
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | free(sendBuf);
|
|---|
| 71 | free(rcvBuf);
|
|---|
| 72 | free(sum);
|
|---|
| 73 | return 0;
|
|---|
| 74 | }
|
|---|