MPI_Allreduce for object of a class

Let's say I have a class named Node. A user defined vector of objects of this class is std::vector<Node> Nodes. Each Part of this vector is built in different processors. Now I want to use the MPI_Allreduce to have the Nodes in all process, but the problem is I don't know how to deal with MPI_Datatype in this case. thanks for your help in advance
Looks like MPI can describe a struct as MPI_Datatype: https://www.open-mpi.org/doc/v4.0/man3/MPI_Type_create_struct.3.php
You probably need an operator for your type too: https://www.open-mpi.org/doc/v3.0/man3/MPI_Op_create.3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include "mpi.h"
using namespace std;

struct Node
{
   int i;
   double x;
   char c;
};


void makeNodetype( MPI_Datatype &Nodetype )
{
   Node n;

   MPI_Datatype types        [3] = {        MPI_INT,     MPI_DOUBLE,       MPI_CHAR };
   int          blocks       [3] = {              1,              1,              1 };
   MPI_Aint     displacements[3] = { (MPI_Aint)&n.i, (MPI_Aint)&n.x, (MPI_Aint)&n.c };
   for ( int i = 1; i < 3; i++ ) displacements[i] -= displacements[0];
   displacements[0] = 0;
   
   MPI_Type_create_struct( 3, blocks, displacements, types, &Nodetype );
   MPI_Type_commit( &Nodetype );
}


int main( int argc, char* argv[] )
{
   int rank;
   Node node;

   MPI_Init( &argc, &argv );
   MPI_Comm_rank( MPI_COMM_WORLD, &rank );

   // Set up datatype
   MPI_Datatype Nodetype;
   makeNodetype( Nodetype );

   if ( rank == 0 ) node = { 42, 3.14159, 'C' };           // Root sets content of node ...
   MPI_Bcast( &node, 1, Nodetype, 0, MPI_COMM_WORLD );     // ... and broadcasts to all

   cout << "Processor " << rank << ": " << node.i << " " << node.x << " " << node.c << endl;

   MPI_Type_free( &Nodetype );
   MPI_Finalize();
}



C:\c++>"C:\Program Files\Microsoft MPI\bin"\mpiexec -n 4 MPI_Struct.exe 
Processor 0: 42 3.14159 C
Processor 2: 42 3.14159 C
Processor 1: 42 3.14159 C
Processor 3: 42 3.14159 C



I have no idea what you are intending to do with MPI_Allreduce.
Last edited on
Thanks for your answers. It was helpful.
Last edited on
Topic archived. No new replies allowed.