Tpetra parallel linear algebra  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Tpetra_Details_printOnce.cpp
1 // @HEADER
2 // *****************************************************************************
3 // Tpetra: Templated Linear Algebra Services Package
4 //
5 // Copyright 2008 NTESS and the Tpetra contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9 
11 
12 #if defined(HAVE_TPETRACORE_MPI)
13 # include "Teuchos_DefaultMpiComm.hpp"
14 #else
15 # include "Teuchos_Comm.hpp"
16 #endif // defined(HAVE_TPETRACORE_MPI)
17 
18 namespace { // (anonymous)
19  bool mpiIsInitialized ()
20  {
21 #if defined(HAVE_TPETRACORE_MPI)
22  int isInitialized = 0;
23  try {
24  (void) MPI_Initialized (&isInitialized);
25  }
26  catch (...) {
27  // Not sure if MPI_Initialized meets strong exception guarantee
28  isInitialized = 0;
29  }
30  return isInitialized != 0;
31 #else
32  return false;
33 #endif // defined(HAVE_TPETRACORE_MPI)
34  }
35 
36  bool mpiIsFinalized ()
37  {
38 #if defined(HAVE_TPETRACORE_MPI)
39  int isFinalized = 0;
40  try {
41  (void) MPI_Finalized (&isFinalized);
42  }
43  catch (...) {
44  // Not sure if MPI_Initialized meets strong exception guarantee
45  isFinalized = 0;
46  }
47  return isFinalized != 0;
48 #else
49  return false;
50 #endif // defined(HAVE_TPETRACORE_MPI)
51  }
52 
53 #if defined(HAVE_TPETRACORE_MPI)
54  bool isMpiComm (const Teuchos::Comm<int>& comm)
55  {
56  using mpi_comm_type = Teuchos::MpiComm<int>;
57  return dynamic_cast<const mpi_comm_type* > (&comm) != nullptr;
58  }
59 #else
60  bool isMpiComm (const Teuchos::Comm<int>& /* comm */ )
61  {
62  return false;
63  }
64 #endif // defined(HAVE_TPETRACORE_MPI)
65 
66  int getRankHarmlessly (const Teuchos::Comm<int>& comm)
67  {
68  if (mpiIsInitialized () && ! mpiIsFinalized () && isMpiComm (comm)) {
69  return comm.getRank ();
70  }
71  else {
72  return 0;
73  }
74  }
75 } // namespace (anonymous)
76 
77 namespace Tpetra {
78  namespace Details {
79  void
80  printOnce (std::ostream& out,
81  const std::string& s,
82  const Teuchos::Comm<int>* comm)
83  {
84  if (comm == nullptr || getRankHarmlessly (*comm) == 0) {
85  out << s;
86  }
87  }
88  } // namespace Details
89 } // namespace Tpetra
bool isInitialized()
Whether Tpetra is in an initialized state.
void printOnce(std::ostream &out, const std::string &s, const Teuchos::Comm< int > *comm)
Print on one process of the given communicator, or at least try to do so (if MPI is not initialized)...
Declaration of Tpetra::Details::printOnce.
bool mpiIsFinalized()
Has MPI_Finalize been called (on this process)?
bool mpiIsInitialized()
Has MPI_Init been called (on this process)?