| 1 |
#include "mpi.h" |
| 2 |
#include <vector> |
| 3 |
#include <cassert> |
| 4 |
#include <stdexcept> |
| 5 |
#include <iostream> |
| 6 |
|
| 7 |
// comment this out to build this file as its own executable |
| 8 |
#define BUILDING_IN_STK |
| 9 |
|
| 10 |
#ifdef BUILDING_IN_STK |
| 11 |
#include "gtest/gtest.h" |
| 12 |
#endif |
| 13 |
|
| 14 |
namespace { |
| 15 |
|
| 16 |
using DType = int; |
| 17 |
const int NVals = 4096; // use fixed number of elements to simplify this |
| 18 |
// example. In the real code the number of |
| 19 |
// elements is unknown, which is why we use |
| 20 |
// MPI_Improbe |
| 21 |
|
| 22 |
// send only to self |
| 23 |
void doCommunication(MPI_Comm comm) |
| 24 |
{ |
| 25 |
MPI_Barrier(comm); |
| 26 |
int comm_size, comm_rank, tag=7; |
| 27 |
MPI_Comm_size(comm, &comm_size); |
| 28 |
MPI_Comm_rank(comm, &comm_rank); |
| 29 |
|
| 30 |
std::vector<DType> send_buf(NVals), recv_buf(NVals); |
| 31 |
MPI_Request send_req, recv_req; |
| 32 |
|
| 33 |
for (int i=0; i < NVals; ++i) |
| 34 |
send_buf[i] = i + comm_rank; |
| 35 |
|
| 36 |
|
| 37 |
// post send |
| 38 |
MPI_Isend(send_buf.data(), NVals*sizeof(DType), MPI_BYTE, comm_rank, tag, comm, &send_req); |
| 39 |
|
| 40 |
// Probe for receives |
| 41 |
while (true) |
| 42 |
{ |
| 43 |
int flag=false; |
| 44 |
MPI_Message message; |
| 45 |
MPI_Status status; |
| 46 |
MPI_Improbe(MPI_ANY_SOURCE, tag, comm, &flag, &message, &status); |
| 47 |
|
| 48 |
if (flag) |
| 49 |
{ |
| 50 |
int count=0; |
| 51 |
MPI_Get_count(&status, MPI_BYTE, &count); |
| 52 |
assert(count == NVals * sizeof(DType)); |
| 53 |
assert(status.MPI_SOURCE == comm_rank); |
| 54 |
|
| 55 |
MPI_Imrecv(recv_buf.data(), count, MPI_BYTE, &message, &recv_req); |
| 56 |
break; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
MPI_Wait(&send_req, MPI_STATUS_IGNORE); |
| 61 |
MPI_Wait(&recv_req, MPI_STATUS_IGNORE); |
| 62 |
|
| 63 |
// check result |
| 64 |
for (int i=0; i < NVals; ++i) |
| 65 |
if (send_buf[i] != recv_buf[i]) |
| 66 |
throw std::runtime_error("recv buffer value not correct"); |
| 67 |
|
| 68 |
MPI_Barrier(comm); |
| 69 |
} |
| 70 |
|
| 71 |
} |
| 72 |
|
| 73 |
#ifdef BUILDING_IN_STK |
| 74 |
TEST(Improbe, Improbe_self) |
| 75 |
{ |
| 76 |
doCommunication(MPI_COMM_WORLD); |
| 77 |
} |
| 78 |
|
| 79 |
#else |
| 80 |
|
| 81 |
int main(int argc, char* argv[]) |
| 82 |
{ |
| 83 |
MPI_Init(&argc, &argv); |
| 84 |
|
| 85 |
doCommunication(MPI_COMM_WORLD); |
| 86 |
|
| 87 |
MPI_Finalize(); |
| 88 |
} |
| 89 |
#endif |