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 #if defined(HAVE_TPETRACORE_MPI)
21  int isInitialized = 0;
22  try {
23  (void)MPI_Initialized(&isInitialized);
24  } catch (...) {
25  // Not sure if MPI_Initialized meets strong exception guarantee
26  isInitialized = 0;
27  }
28  return isInitialized != 0;
29 #else
30  return false;
31 #endif // defined(HAVE_TPETRACORE_MPI)
32 }
33 
34 bool mpiIsFinalized() {
35 #if defined(HAVE_TPETRACORE_MPI)
36  int isFinalized = 0;
37  try {
38  (void)MPI_Finalized(&isFinalized);
39  } catch (...) {
40  // Not sure if MPI_Initialized meets strong exception guarantee
41  isFinalized = 0;
42  }
43  return isFinalized != 0;
44 #else
45  return false;
46 #endif // defined(HAVE_TPETRACORE_MPI)
47 }
48 
49 #if defined(HAVE_TPETRACORE_MPI)
50 bool isMpiComm(const Teuchos::Comm<int>& comm) {
51  using mpi_comm_type = Teuchos::MpiComm<int>;
52  return dynamic_cast<const mpi_comm_type*>(&comm) != nullptr;
53 }
54 #else
55 bool isMpiComm(const Teuchos::Comm<int>& /* comm */) {
56  return false;
57 }
58 #endif // defined(HAVE_TPETRACORE_MPI)
59 
60 int getRankHarmlessly(const Teuchos::Comm<int>& comm) {
61  if (mpiIsInitialized() && !mpiIsFinalized() && isMpiComm(comm)) {
62  return comm.getRank();
63  } else {
64  return 0;
65  }
66 }
67 } // namespace
68 
69 namespace Tpetra {
70 namespace Details {
71 void printOnce(std::ostream& out,
72  const std::string& s,
73  const Teuchos::Comm<int>* comm) {
74  if (comm == nullptr || getRankHarmlessly(*comm) == 0) {
75  out << s;
76  }
77 }
78 } // namespace Details
79 } // 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)?