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 gathervPrint(std::ostream& out,
18  const std::string& s,
19  const Teuchos::Comm<int>& comm) {
20  using Teuchos::ArrayRCP;
21  using Teuchos::CommRequest;
22  using Teuchos::ireceive;
23  using Teuchos::isend;
24  using Teuchos::outArg;
25  using Teuchos::RCP;
26  using Teuchos::wait;
27 
28  const int myRank = comm.getRank();
29  const int rootRank = 0;
30  if (myRank == rootRank) {
31  out << s; // Proc 0 prints its buffer first
32  }
33 
34  const int numProcs = comm.getSize();
35  const int sizeTag = 42;
36  const int msgTag = 43;
37 
38  ArrayRCP<size_t> sizeBuf(1);
39  ArrayRCP<char> msgBuf; // to be resized later
40  RCP<CommRequest<int> > req;
41 
42  for (int p = 1; p < numProcs; ++p) {
43  if (myRank == p) {
44  sizeBuf[0] = s.size();
45  req = isend<int, size_t>(sizeBuf, rootRank, sizeTag, comm);
46  (void)wait<int>(comm, outArg(req));
47 
48  const size_t msgSize = s.size();
49  msgBuf.resize(msgSize + 1); // for the '\0'
50  std::copy(s.begin(), s.end(), msgBuf.begin());
51  msgBuf[msgSize] = '\0';
52 
53  req = isend<int, char>(msgBuf, rootRank, msgTag, comm);
54  (void)wait<int>(comm, outArg(req));
55  } else if (myRank == rootRank) {
56  sizeBuf[0] = 0; // just a precaution
57  req = ireceive<int, size_t>(sizeBuf, p, sizeTag, comm);
58  (void)wait<int>(comm, outArg(req));
59 
60  const size_t msgSize = sizeBuf[0];
61  msgBuf.resize(msgSize + 1); // for the '\0'
62  req = ireceive<int, char>(msgBuf, p, msgTag, comm);
63  (void)wait<int>(comm, outArg(req));
64 
65  std::string msg(msgBuf.getRawPtr());
66  out << msg;
67  }
68  }
69 }
70 
71 } // namespace Details
72 } // 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.