DEV Community

Watson
Watson

Posted on

1

How to Send Pair with Open MPI

Hey guys.
I'm a beginner of Open MPI.
When I wanted to send some std::pair onjects from a node to another, I found out the fact that there are no Datatype of std::pair.
You can use only the datatypes in Open MPI as bellow.

MPI Datatype C++ Datatype
MPI::CHAR char
MPI::SHORT signed short
MPI::INT signed int
MPI::LONG signed long
MPI::LONG_LONG signed long long
MPI::SIGNED_CHAR signed char
MPI::UNSIGNED_CHAR unsigned char
MPI::UNSIGNED_SHORT unsigned short
MPI::UNSIGNED unsigned int
MPI::UNSIGNED_LONG unsigned long int
MPI::UNSIGNED_LONG_LONG unsigned long long
MPI::FLOAT float
MPI::DOUBLE double
MPI::LONG_DOUBLE long double
MPI::BOOL bool
MPI::COMPLEX Complex
MPI::DOUBLE_COMPLEX Complex
MPI::LONG_DOUBLE_COMPLEX Complex
MPI::WCHAR wchar_t
MPI::BYTE
MPI::PACKED

You can see only basic types and it's natural to do so because developers use variety of custom types and Open MPI can't prepare for all types of them.

I think the most flexible one is MPI::BYTE.
So, I used it to send std::pair.
You can easly calculate the total size of pairs in 1 byte increments by using the "sizeof" function.

Here is the example code.

#include "mpi.h"
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char **argv) {
  int rank, numprocs;
  int namelen;
  vector<pair<int, int>> send_buf = {make_pair(0, 1), make_pair(2, 3)};
  vector<pair<int, int>> recv_buf(2);

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  if(rank == 0){
    MPI_Send((void*)send_buf.data(), sizeof(pair<int,int>)*2, MPI_BYTE, 1, 0, MPI_COMM_WORLD);
  }

  if(rank == 1){
     MPI_Recv((void*)recv_buf.data(), sizeof(pair<int,int>)*2, MPI_BYTE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
     cout << recv_buf[0].first << ":" << recv_buf[0].second << endl;
     cout << recv_buf[1].first << ":" << recv_buf[1].second << endl;
  }
  MPI_Finalize();
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Enjoy hacking!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay