Sierra Toolkit  Version of the Day
BroadcastArg.cpp
1 /*------------------------------------------------------------------------*/
2 /* Copyright 2010 Sandia Corporation. */
3 /* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */
4 /* license for use of this work by or on behalf of the U.S. Government. */
5 /* Export of this program may require a license from the */
6 /* United States Government. */
7 /*------------------------------------------------------------------------*/
8 
9 #include <string>
10 
11 #include <stk_util/parallel/BroadcastArg.hpp>
12 
13 namespace stk_classic {
14 
16  stk_classic::ParallelMachine parallel_machine,
17  int argc,
18  char ** argv)
19 {
20 #ifdef STK_HAS_MPI
21  int rank = stk_classic::parallel_machine_rank(parallel_machine);
22 #else
23  int rank = 0;
24 #endif
25 
26  size_t buffer_length = 0;
27  char * buffer = 0;
28 
29 // Populate m_argc, m_buffer and buffer_length on rank 0 or !STK_HAS_MPI
30  if (rank == 0) {
31  m_argc = argc;
32 
33  std::string s;
34  for (int i = 0; i < argc; ++i) {
35  s += argv[i];
36  s += '\0';
37  }
38 
39  buffer_length = s.size();
40  buffer = new char[buffer_length];
41 
42  std::copy(s.begin(), s.end(), buffer);
43  }
44 
45 // if STK_HAS_MPI, broadcast m_argc, buffer and buffer_length to processors
46 #ifdef STK_HAS_MPI
47  if (rank == 0) {
48  int lengths_buffer[2];
49  lengths_buffer[0] = m_argc;
50  lengths_buffer[1] = buffer_length;
51 
52  MPI_Bcast(lengths_buffer, 2, MPI_INT, 0, parallel_machine);
53 
54  MPI_Bcast(buffer, buffer_length, MPI_BYTE, 0, parallel_machine);
55  }
56  else {
57  int lengths_buffer[2];
58  MPI_Bcast(lengths_buffer, 2, MPI_INT, 0, parallel_machine);
59 
60  m_argc = lengths_buffer[0];
61  buffer_length = lengths_buffer[1];
62  buffer = new char[buffer_length];
63 
64  MPI_Bcast(buffer, buffer_length, MPI_BYTE, 0, parallel_machine);
65  }
66 #endif
67 
68 // Populate the m_argv
69  m_argv = new char *[m_argc];
70 
71 // argv[0] will always point to buffer, so argv[0] needs to be deleted by the destructor
72  char *c = &buffer[0];
73  for (int i = 0; i < argc; ++i) {
74  m_argv[i] = c;
75  while (*c)
76  ++c;
77  ++c;
78  }
79 }
80 
81 
83 {
84  delete[] m_argv[0];
85  delete[] m_argv;
86 }
87 
88 } // namespace stk_classic
BroadcastArg(ParallelMachine parallel_machine, int argc, char **argv)
int m_argc
The broadcasted argc.
char ** m_argv
The broadcasted argv.
unsigned parallel_machine_rank(ParallelMachine parallel_machine)
Member function parallel_machine_rank ...
Definition: Parallel.cpp:29
Sierra Toolkit.
MPI_Comm ParallelMachine
Definition: Parallel.hpp:32