| 1 | /**
|
|---|
| 2 | * This program should deadlock but it doesn't.
|
|---|
| 3 | * Not all processes are executing the collective
|
|---|
| 4 | * operations in the same order.
|
|---|
| 5 | */
|
|---|
| 6 | #include<mpi.h>
|
|---|
| 7 | #include<stdlib.h>
|
|---|
| 8 | #include<assert.h>
|
|---|
| 9 | #include<stdio.h>
|
|---|
| 10 |
|
|---|
| 11 | int main()
|
|---|
| 12 | {
|
|---|
| 13 | int argc;
|
|---|
| 14 | char** argv;
|
|---|
| 15 | int rank;
|
|---|
| 16 | int procs;
|
|---|
| 17 | int* sendBuf;
|
|---|
| 18 | int* rcvBuf;
|
|---|
| 19 | int* sum;
|
|---|
| 20 |
|
|---|
| 21 | MPI_Init(&argc,&argv);
|
|---|
| 22 | MPI_Comm_size(MPI_COMM_WORLD, &procs);
|
|---|
| 23 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 24 |
|
|---|
| 25 | if (rank == 0) {
|
|---|
| 26 | sendBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 27 | sum = (int*)malloc(sizeof(int)*procs);
|
|---|
| 28 | for(int i=0; i < procs; i++){
|
|---|
| 29 | sendBuf[i] = i;
|
|---|
| 30 | sum[i] = 0;
|
|---|
| 31 | }
|
|---|
| 32 | }else{
|
|---|
| 33 | sum = (int*)malloc(sizeof(int));
|
|---|
| 34 | sendBuf = (int*)malloc(sizeof(int));
|
|---|
| 35 | }
|
|---|
| 36 | rcvBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 37 |
|
|---|
| 38 | MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 39 |
|
|---|
| 40 | *sendBuf = *rcvBuf;
|
|---|
| 41 |
|
|---|
| 42 | if(rank % 2)
|
|---|
| 43 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 44 | else
|
|---|
| 45 | MPI_Scatter(sum, 1, MPI_INT, sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 46 |
|
|---|
| 47 | printf("Vector process %d is: (", rank);
|
|---|
| 48 | for(int i=0; i<procs; i++){
|
|---|
| 49 | printf("%d", rcvBuf[i]);
|
|---|
| 50 | if(i != procs-1)
|
|---|
| 51 | printf(", ");
|
|---|
| 52 | }
|
|---|
| 53 | printf(")\n");
|
|---|
| 54 |
|
|---|
| 55 | if(rank%2)
|
|---|
| 56 | MPI_Scatter(sum, 1, MPI_INT, sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 57 | else
|
|---|
| 58 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 59 |
|
|---|
| 60 | MPI_Reduce(rcvBuf, sum, procs, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
|
|---|
| 61 |
|
|---|
| 62 | if(rank == 0){
|
|---|
| 63 | printf("Vector sum is: (");
|
|---|
| 64 | for(int i=0; i<procs; i++){
|
|---|
| 65 | printf("%d", sum[i]);
|
|---|
| 66 | if(i != procs-1)
|
|---|
| 67 | printf(", ");
|
|---|
| 68 | }
|
|---|
| 69 | printf(")\n");
|
|---|
| 70 | }
|
|---|
| 71 |
|
|---|
| 72 | free(sendBuf);
|
|---|
| 73 | free(rcvBuf);
|
|---|
| 74 | free(sum);
|
|---|
| 75 | return 0;
|
|---|
| 76 | }
|
|---|