MPI_first_template
greetings.cpp
Go to the documentation of this file.
1 #include "greetings.h"
2 #include <cassert>
3 #include <cstring>
4 #include <iostream>
5 #include <mpi.h> // MPI
6 #include <string>
7 using namespace std;
8 
9 // see http://www.open-mpi.org/doc/current
10 // for details on MPI functions
11 
12 void greetings(MPI_Comm const &icomm)
13 {
14  int myrank, numprocs;
15  MPI_Comm_rank(icomm, &myrank); // my MPI-rank
16  MPI_Comm_size(icomm, &numprocs); // #MPI processes
17  char *name = new char [MPI_MAX_PROCESSOR_NAME],
18  *chbuf = new char [MPI_MAX_PROCESSOR_NAME];
19 
20  int reslen, ierr;
21  MPI_Get_processor_name( name, &reslen);
22 
23  if (0==myrank) {
24  cout << " " << myrank << " runs on " << name << endl;
25  for (int i = 1; i < numprocs; ++i) {
26  MPI_Status stat;
27  stat.MPI_ERROR = 0; // M U S T be initialized!!
28 
29  ierr = MPI_Recv(chbuf, MPI_MAX_PROCESSOR_NAME, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, &stat);
30  assert(0==ierr);
31 
32  cout << " " << stat.MPI_SOURCE << " runs on " << chbuf;
33  int count;
34  MPI_Get_count(&stat, MPI_CHAR, &count); // size of received data
35  cout << " (length: " << count << " )" << endl;
36  // stat.Get_error() // Error code
37  }
38  }
39  else {
40  int dest = 0;
41  ierr = MPI_Send(name, strlen(name) + 1, MPI_CHAR, dest, myrank, icomm);
42  assert(0==ierr);
43  }
44  delete [] chbuf;
45  delete [] name;
46  return;
47 }
48 
49 
50 void greetings_cpp(MPI_Comm const &icomm)
51 {
52  int myrank, numprocs;
53  MPI_Comm_rank(icomm, &myrank); // my MPI-rank
54  MPI_Comm_size(icomm, &numprocs); // #MPI processes
55  string name(MPI_MAX_PROCESSOR_NAME,'#'), // C++
56  recvbuf(MPI_MAX_PROCESSOR_NAME,'#'); // C++: receive buffer, don't change size
57 
58  int reslen, ierr;
59  MPI_Get_processor_name(name.data(), &reslen);
60  name.resize(reslen); // C++
61 
62  if (0==myrank) {
63  cout << " " << myrank << " runs on " << name << endl;
64  for (int i = 1; i < numprocs; ++i) {
65  MPI_Status stat;
66  stat.MPI_ERROR = 0; // M U S T be initialized!!
67 
68  ierr = MPI_Recv(recvbuf.data(), MPI_MAX_PROCESSOR_NAME, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, &stat);
69  assert(0==ierr);
70 
71  int count;
72  MPI_Get_count(&stat, MPI_CHAR, &count); // size of received data
73  string const chbuf(recvbuf,0,count); // C++
74  cout << " " << stat.MPI_SOURCE << " runs on " << chbuf;
75  cout << " (length: " << count << " )" << endl;
76  // stat.Get_error() // Error code
77  }
78  }
79  else {
80  int dest = 0;
81  ierr = MPI_Send(name.data(), name.size(), MPI_CHAR, dest, myrank, icomm);
82  assert(0==ierr);
83  }
84  return;
85 }
greetings.h
greetings_cpp
void greetings_cpp(MPI_Comm const &icomm)
Definition: greetings.cpp:50
greetings
void greetings(MPI_Comm const &icomm)
Definition: greetings.cpp:12