| 1 | /* trickydl.c : A tricky deadlocking MPI program.
|
|---|
| 2 | * Author: Stephen F. Siegel
|
|---|
| 3 | * Date: 2016 Jul 18
|
|---|
| 4 | */
|
|---|
| 5 | #include <mpi.h>
|
|---|
| 6 | #include <assert.h>
|
|---|
| 7 |
|
|---|
| 8 | int nprocs, rank, tag=0;
|
|---|
| 9 | MPI_Comm comm = MPI_COMM_WORLD;
|
|---|
| 10 | MPI_Status *stat = MPI_STATUS_IGNORE;
|
|---|
| 11 | int ignore;
|
|---|
| 12 | int *null = &ignore;
|
|---|
| 13 |
|
|---|
| 14 | /* Detects buffering.
|
|---|
| 15 | * If all communication is synchronous, rank 0 must return 0.
|
|---|
| 16 | * If communication can buffer, rank 0 could return 0 or 1.
|
|---|
| 17 | * In any case: this function is deadlock-free.
|
|---|
| 18 | */
|
|---|
| 19 | int f() {
|
|---|
| 20 | int buf;
|
|---|
| 21 |
|
|---|
| 22 | if (rank == 0) {
|
|---|
| 23 | MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, tag, comm, stat);
|
|---|
| 24 | MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, tag, comm, stat);
|
|---|
| 25 | return buf;
|
|---|
| 26 | } else if (rank == 1) {
|
|---|
| 27 | MPI_Recv(null, 0, MPI_INT, 2, tag, comm, stat);
|
|---|
| 28 | buf = 0;
|
|---|
| 29 | MPI_Send(&buf, 1, MPI_INT, 0, tag, comm);
|
|---|
| 30 | } else if (rank == 2) {
|
|---|
| 31 | buf = 1;
|
|---|
| 32 | MPI_Send(&buf, 1, MPI_INT, 0, tag, comm);
|
|---|
| 33 | MPI_Send(null, 0, MPI_INT, 1, tag, comm);
|
|---|
| 34 | }
|
|---|
| 35 | return 0;
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | /* Deadlocks iff all communication is synchronous.
|
|---|
| 39 | * As long as one 0-byte message can be buffered,
|
|---|
| 40 | * no deadlock is possible. */
|
|---|
| 41 | void g() {
|
|---|
| 42 | if (rank == 0) {
|
|---|
| 43 | MPI_Send(null, 0, MPI_INT, 1, tag, comm);
|
|---|
| 44 | MPI_Recv(null, 0, MPI_INT, 1, tag, comm, stat);
|
|---|
| 45 | } else if (rank == 1) {
|
|---|
| 46 | MPI_Send(null, 0, MPI_INT, 0, tag, comm);
|
|---|
| 47 | MPI_Recv(null, 0, MPI_INT, 0, tag, comm, stat);
|
|---|
| 48 | }
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | int main() {
|
|---|
| 52 | MPI_Init(NULL, NULL);
|
|---|
| 53 | MPI_Comm_size(comm, &nprocs);
|
|---|
| 54 | MPI_Comm_rank(comm, &rank);
|
|---|
| 55 | assert(nprocs >= 3);
|
|---|
| 56 |
|
|---|
| 57 | int x = f();
|
|---|
| 58 |
|
|---|
| 59 | MPI_Barrier(comm);
|
|---|
| 60 | MPI_Bcast(&x, 1, MPI_INT, 0, comm);
|
|---|
| 61 | if (x) { g(); }
|
|---|
| 62 | MPI_Finalize();
|
|---|
| 63 | }
|
|---|