| 1 | /**
|
|---|
| 2 | * This example has a deadlock because collective operations are not called in the same
|
|---|
| 3 | * order for all processes.
|
|---|
| 4 | */
|
|---|
| 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 |
|
|---|
| 20 | MPI_Init(&argc,&argv);
|
|---|
| 21 | MPI_Comm_size(MPI_COMM_WORLD, &procs);
|
|---|
| 22 | MPI_Comm_rank(MPI_COMM_WORLD, &rank);
|
|---|
| 23 |
|
|---|
| 24 | if (rank == 0) {
|
|---|
| 25 | sendBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 26 | //rcvBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 27 | for(int i=0; i < procs; i++)
|
|---|
| 28 | sendBuf[i] = i;
|
|---|
| 29 | }else{
|
|---|
| 30 | sendBuf = (int*)malloc(sizeof(int));
|
|---|
| 31 | }
|
|---|
| 32 | rcvBuf = (int*)malloc(sizeof(int)*procs);
|
|---|
| 33 |
|
|---|
| 34 | if(rank%2)
|
|---|
| 35 | MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 36 | else
|
|---|
| 37 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 38 |
|
|---|
| 39 | *sendBuf = *rcvBuf + rank;
|
|---|
| 40 |
|
|---|
| 41 | if(rank%2)
|
|---|
| 42 | MPI_Allgather(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, MPI_COMM_WORLD);
|
|---|
| 43 | else
|
|---|
| 44 | MPI_Scatter(sendBuf, 1, MPI_INT, rcvBuf, 1, MPI_INT, 0, MPI_COMM_WORLD);
|
|---|
| 45 |
|
|---|
| 46 | printf("receive buffer of process %d:\n", rank);
|
|---|
| 47 | for(int i=0; i<procs; i++){
|
|---|
| 48 | printf("rcvBuf[%d]=%d\n", i, rcvBuf[i]);
|
|---|
| 49 | assert(i*2 == rcvBuf[i]);
|
|---|
| 50 | }
|
|---|
| 51 | free(sendBuf);
|
|---|
| 52 | free(rcvBuf);
|
|---|
| 53 | return 0;
|
|---|
| 54 | }
|
|---|