dune-common  2.2.0
mpihelper.hh
Go to the documentation of this file.
1 // $Id: $
2 #ifndef DUNE_MPIHELPER
3 #define DUNE_MPIHELPER
4 
5 #include <cassert>
7 #if HAVE_MPI
8 #include"mpi.h"
10 #endif
11 
12 #include "stdstreams.hh"
13 
14 namespace Dune
15 {
66  {
67  public:
68  enum{
73  isFake = true
74  };
75 
80 
88  {
89  static MPICommunicator comm;
90  return comm;
91  }
92 
100  {
101  return getCommunicator();
102  }
103 
104 
105 
108  {
110  }
111 
127  static FakeMPIHelper& instance(int argc, char** argv)
128  {
129  // create singleton instance
130  static FakeMPIHelper singleton;
131  return singleton;
132  }
133 
137  int rank () const { return 0; }
141  int size () const { return 1; }
142 
143  private:
144  FakeMPIHelper() {}
145  FakeMPIHelper(const FakeMPIHelper&);
146  FakeMPIHelper& operator=(const FakeMPIHelper);
147  };
148 
149 #if HAVE_MPI
150 
156  class MPIHelper
157  {
158  public:
159  enum{
164  isFake = false
165  };
166 
170  typedef MPI_Comm MPICommunicator;
171 
179  {
180  return MPI_COMM_WORLD;
181  }
182 
190  {
191  return MPI_COMM_SELF;
192  }
193 
196  {
198  }
214  static MPIHelper& instance(int& argc, char**& argv)
215  {
216  // create singleton instance
217  static MPIHelper singleton (argc, argv);
218  return singleton;
219  }
220 
224  int rank () const { return rank_; }
228  int size () const { return size_; }
229 
230  private:
231  int rank_;
232  int size_;
233  void prevent_warning(int){}
234 
236  MPIHelper(int& argc, char**& argv)
237  {
238 #if MPI_2
239  int wasInitialized = -1;
240  MPI_Initialized( &wasInitialized );
241  if(!wasInitialized)
242 #endif
243  {
244  rank_ = -1;
245  size_ = -1;
246  static int is_initialized = MPI_Init(&argc, &argv);
247  prevent_warning(is_initialized);
248  }
249 
250  MPI_Comm_rank(MPI_COMM_WORLD,&rank_);
251  MPI_Comm_size(MPI_COMM_WORLD,&size_);
252 
253  assert( rank_ >= 0 );
254  assert( size_ >= 1 );
255 
256  dverb << "Called MPI_Init on p=" << rank_ << "!" << std::endl;
257  }
259  ~MPIHelper()
260  {
261 #ifdef MPI_2
262  int wasFinalized = -1;
263  MPI_Finalized( &wasFinalized );
264  if(!wasFinalized){
265 #endif
266  MPI_Finalize();
267  dverb << "Called MPI_Finalize on p=" << rank_ << "!" <<std::endl;
268 #ifdef MPI_2
269  }
270 
271 #endif
272  }
273  MPIHelper(const MPIHelper&);
274  MPIHelper& operator=(const MPIHelper);
275  };
276 #else
277  // We do not have MPI therefore FakeMPIHelper
278  // is the MPIHelper
283  typedef FakeMPIHelper MPIHelper;
284 
285 #endif
286 
287 } // end namespace Dune
288 #endif