| 1 | #include "mpi.h"
|
|---|
| 2 | #include "assert.h"
|
|---|
| 3 |
|
|---|
| 4 | int many_to_one () {
|
|---|
| 5 | int size;
|
|---|
| 6 | int rank;
|
|---|
| 7 | MPI_Comm comm = MPI_COMM_WORLD;
|
|---|
| 8 | MPI_Datatype type = MPI_INT;
|
|---|
| 9 |
|
|---|
| 10 | MPI_Comm_size (comm, &size);
|
|---|
| 11 | MPI_Comm_rank (comm, &rank);
|
|---|
| 12 |
|
|---|
| 13 | if (rank != 0) {
|
|---|
| 14 | int dat[5] = {rank * size + 1, rank * size, rank * size + 2,
|
|---|
| 15 | rank * size, rank * size + 3};
|
|---|
| 16 |
|
|---|
| 17 | MPI_Send(dat, 1, MPI_INT, 0, 1, comm);
|
|---|
| 18 | MPI_Send(dat + 1, 1, MPI_INT, 0, 0, comm);
|
|---|
| 19 | MPI_Send(dat + 2, 1, MPI_INT, 0, 2, comm);
|
|---|
| 20 | MPI_Send(dat + 3, 1, MPI_INT, 0, 0, comm);
|
|---|
| 21 | MPI_Send(dat + 4, 1, MPI_INT, 0, 3, comm);
|
|---|
| 22 | } else {
|
|---|
| 23 | int ub = 5 * (size-1);
|
|---|
| 24 | int rbuf[ub];
|
|---|
| 25 | MPI_Request reqs[ub];
|
|---|
| 26 | MPI_Status statuses[ub];
|
|---|
| 27 | int oft = 0;
|
|---|
| 28 |
|
|---|
| 29 | for (int i = 1; i < size; i++) {
|
|---|
| 30 | MPI_Irecv(rbuf + oft, 1, MPI_INT, i, MPI_ANY_TAG, comm, reqs + oft);
|
|---|
| 31 | oft++;
|
|---|
| 32 | }
|
|---|
| 33 | for (int i = 1; i < size; i++) {
|
|---|
| 34 | MPI_Irecv(rbuf + oft, 1, MPI_INT, MPI_ANY_SOURCE, 0, comm, reqs + oft);
|
|---|
| 35 | oft++;
|
|---|
| 36 | }
|
|---|
| 37 | for (int i = 1; i < size; i++) {
|
|---|
| 38 | MPI_Irecv(rbuf + oft, 1, MPI_INT, i, MPI_ANY_TAG, comm, reqs + oft);
|
|---|
| 39 | oft++;
|
|---|
| 40 | }
|
|---|
| 41 | for (int i = 1; i < size; i++) {
|
|---|
| 42 | MPI_Irecv(rbuf + oft, 1, MPI_INT, MPI_ANY_SOURCE, 0, comm, reqs + oft);
|
|---|
| 43 | oft++;
|
|---|
| 44 | }
|
|---|
| 45 | for (int i = 1; i < size; i++) {
|
|---|
| 46 | MPI_Irecv(rbuf + oft, 1, MPI_INT, i, MPI_ANY_TAG, comm, reqs + oft);
|
|---|
| 47 | oft++;
|
|---|
| 48 | }
|
|---|
| 49 | MPI_Waitall(ub, reqs, statuses);
|
|---|
| 50 | for (int i = 0; i < ub; i++) {
|
|---|
| 51 | int src = statuses[i].MPI_SOURCE;
|
|---|
| 52 | int tag = statuses[i].MPI_TAG;
|
|---|
| 53 |
|
|---|
| 54 | assert (rbuf[i] == src * size + tag);
|
|---|
| 55 | }
|
|---|
| 56 | }
|
|---|
| 57 | return 0;
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | int main() {
|
|---|
| 61 | MPI_Init(NULL, NULL);
|
|---|
| 62 | many_to_one();
|
|---|
| 63 | MPI_Finalize();
|
|---|
| 64 | return 0;
|
|---|
| 65 | }
|
|---|