| 1 | /* This program illustrates that using a fixed buffer
|
|---|
| 2 | * size model to detect potential deadlocks is not sound.
|
|---|
| 3 | * Run with nprocs=3.
|
|---|
| 4 | *
|
|---|
| 5 | * If a 0-buffer-size model is used: f must return 0 on rank 0,
|
|---|
| 6 | * therefore g is never called, and there is no deadlock.
|
|---|
| 7 | *
|
|---|
| 8 | * If a positive-buffer-size model is used: f may return 0 or 1 on
|
|---|
| 9 | * rank 0, but g will not deadlock because at least one send will be
|
|---|
| 10 | * buffered; again, no deadlock.
|
|---|
| 11 | *
|
|---|
| 12 | * However in reality the program can deadlock: f() could return 1 on
|
|---|
| 13 | * rank 0, and then the sends in g() could be forced to synchronize
|
|---|
| 14 | * regardless, leading to deadlock.
|
|---|
| 15 | *
|
|---|
| 16 | * Author: Stephen Siegel
|
|---|
| 17 | */
|
|---|
| 18 | #include <mpi.h>
|
|---|
| 19 | #include <assert.h>
|
|---|
| 20 | #include <stdlib.h>
|
|---|
| 21 |
|
|---|
| 22 | int nprocs, rank, tag=0;
|
|---|
| 23 | MPI_Comm comm = MPI_COMM_WORLD;
|
|---|
| 24 | MPI_Status *stat = MPI_STATUS_IGNORE;
|
|---|
| 25 |
|
|---|
| 26 | /* If all communication is synchronous, rank 0 must return 0.
|
|---|
| 27 | * If communication can buffer, rank 0 could return 0 or 1. */
|
|---|
| 28 | int f() {
|
|---|
| 29 | int buf;
|
|---|
| 30 | if (rank == 0) {
|
|---|
| 31 | MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, tag, comm, stat);
|
|---|
| 32 | MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, tag, comm, stat);
|
|---|
| 33 | return buf;
|
|---|
| 34 | } else if (rank == 1) {
|
|---|
| 35 | MPI_Recv(NULL, 0, MPI_INT, 2, tag, comm, stat);
|
|---|
| 36 | buf = 0;
|
|---|
| 37 | MPI_Send(&buf, 1, MPI_INT, 0, tag, comm);
|
|---|
| 38 | } else if (rank == 2) {
|
|---|
| 39 | buf = 1;
|
|---|
| 40 | MPI_Send(&buf, 1, MPI_INT, 0, tag, comm);
|
|---|
| 41 | MPI_Send(NULL, 0, MPI_INT, 1, tag, comm);
|
|---|
| 42 | }
|
|---|
| 43 | return 0;
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 | /* Deadlocks iff all communication is synchronous. */
|
|---|
| 47 | void g() {
|
|---|
| 48 | if (rank == 0) {
|
|---|
| 49 | MPI_Send(NULL, 0, MPI_INT, 1, tag, comm);
|
|---|
| 50 | MPI_Recv(NULL, 0, MPI_INT, 1, tag, comm, stat);
|
|---|
| 51 | } else if (rank == 1) {
|
|---|
| 52 | MPI_Send(NULL, 0, MPI_INT, 0, tag, comm);
|
|---|
| 53 | MPI_Recv(NULL, 0, MPI_INT, 0, tag, comm, stat);
|
|---|
| 54 | }
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | /* May or may not deadlock */
|
|---|
| 58 | int main(int argc, char * argv[]) {
|
|---|
| 59 | MPI_Init(&argc, &argv);
|
|---|
| 60 | MPI_Comm_size(comm, &nprocs);
|
|---|
| 61 | MPI_Comm_rank(comm, &rank);
|
|---|
| 62 | assert(nprocs >= 3);
|
|---|
| 63 | int x = f();
|
|---|
| 64 | MPI_Barrier(comm);
|
|---|
| 65 | MPI_Bcast(&x, 1, MPI_INT, 0, comm);
|
|---|
| 66 | if (x) g();
|
|---|
| 67 | MPI_Finalize();
|
|---|
| 68 | }
|
|---|