Tpetra parallel linear algebra  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Tpetra_Details_gathervPrint.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 #include <Teuchos_CommHelpers.hpp>
12 #include <algorithm>
13 
14 namespace Tpetra {
15 namespace Details {
16 
17 void
18 gathervPrint (std::ostream& out,
19  const std::string& s,
20  const Teuchos::Comm<int>& comm)
21 {
22  using Teuchos::ArrayRCP;
23  using Teuchos::CommRequest;
24  using Teuchos::ireceive;
25  using Teuchos::isend;
26  using Teuchos::outArg;
27  using Teuchos::RCP;
28  using Teuchos::wait;
29 
30  const int myRank = comm.getRank ();
31  const int rootRank = 0;
32  if (myRank == rootRank) {
33  out << s; // Proc 0 prints its buffer first
34  }
35 
36  const int numProcs = comm.getSize ();
37  const int sizeTag = 42;
38  const int msgTag = 43;
39 
40  ArrayRCP<size_t> sizeBuf (1);
41  ArrayRCP<char> msgBuf; // to be resized later
42  RCP<CommRequest<int> > req;
43 
44  for (int p = 1; p < numProcs; ++p) {
45  if (myRank == p) {
46  sizeBuf[0] = s.size ();
47  req = isend<int, size_t> (sizeBuf, rootRank, sizeTag, comm);
48  (void) wait<int> (comm, outArg (req));
49 
50  const size_t msgSize = s.size ();
51  msgBuf.resize (msgSize + 1); // for the '\0'
52  std::copy (s.begin (), s.end (), msgBuf.begin ());
53  msgBuf[msgSize] = '\0';
54 
55  req = isend<int, char> (msgBuf, rootRank, msgTag, comm);
56  (void) wait<int> (comm, outArg (req));
57  }
58  else if (myRank == rootRank) {
59  sizeBuf[0] = 0; // just a precaution
60  req = ireceive<int, size_t> (sizeBuf, p, sizeTag, comm);
61  (void) wait<int> (comm, outArg (req));
62 
63  const size_t msgSize = sizeBuf[0];
64  msgBuf.resize (msgSize + 1); // for the '\0'
65  req = ireceive<int, char> (msgBuf, p, msgTag, comm);
66  (void) wait<int> (comm, outArg (req));
67 
68  std::string msg (msgBuf.getRawPtr ());
69  out << msg;
70  }
71  }
72 }
73 
74 } // namespace Details
75 } // namespace Tpetra
Declaration of a function that prints strings from each process.
void gathervPrint(std::ostream &out, const std::string &s, const Teuchos::Comm< int > &comm)
On Process 0 in the given communicator, print strings from each process in that communicator, in rank order.