Sierra Toolkit Version of the Day
BroadcastArg.cpp
00001 /*------------------------------------------------------------------------*/
00002 /*                 Copyright 2010 Sandia Corporation.                     */
00003 /*  Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive   */
00004 /*  license for use of this work by or on behalf of the U.S. Government.  */
00005 /*  Export of this program may require a license from the                 */
00006 /*  United States Government.                                             */
00007 /*------------------------------------------------------------------------*/
00008 
00009 #include <string>
00010 
00011 #include <stk_util/parallel/BroadcastArg.hpp>
00012 
00013 namespace stk {
00014 
00015 BroadcastArg::BroadcastArg(
00016   stk::ParallelMachine  parallel_machine,
00017   int                   argc,
00018   char **               argv)
00019 {
00020 #ifdef STK_HAS_MPI
00021   int rank = stk::parallel_machine_rank(parallel_machine);
00022 #else
00023   int rank = 0;
00024 #endif
00025 
00026   size_t buffer_length = 0;
00027   char * buffer = 0;
00028   
00029 // Populate m_argc, m_buffer and buffer_length on rank 0 or !STK_HAS_MPI
00030   if (rank == 0) {
00031     m_argc = argc;
00032 
00033     std::string s;
00034     for (int i = 0; i < argc; ++i) {
00035       s += argv[i];
00036       s += '\0';
00037     }
00038     
00039     buffer_length = s.size();
00040     buffer = new char[buffer_length];
00041     
00042     std::copy(s.begin(), s.end(), buffer);
00043   }
00044 
00045 // if STK_HAS_MPI, broadcast m_argc, buffer and buffer_length to processors
00046 #ifdef STK_HAS_MPI
00047   if (rank == 0) {
00048     int lengths_buffer[2];
00049     lengths_buffer[0] = m_argc;
00050     lengths_buffer[1] = buffer_length;
00051     
00052     MPI_Bcast(lengths_buffer, 2, MPI_INT, 0, parallel_machine);
00053 
00054     MPI_Bcast(buffer, buffer_length, MPI_BYTE, 0, parallel_machine);
00055   }
00056   else {
00057     int lengths_buffer[2];
00058     MPI_Bcast(lengths_buffer, 2, MPI_INT, 0, parallel_machine);
00059 
00060     m_argc = lengths_buffer[0];
00061     buffer_length = lengths_buffer[1];
00062     buffer = new char[buffer_length];
00063     
00064     MPI_Bcast(buffer, buffer_length, MPI_BYTE, 0, parallel_machine); 
00065   }
00066 #endif
00067     
00068 // Populate the m_argv
00069   m_argv = new char *[m_argc];
00070   
00071 // argv[0] will always point to buffer, so argv[0] needs to be deleted by the destructor
00072   char *c = &buffer[0];
00073   for (int i = 0; i < argc; ++i) {
00074     m_argv[i] = c;
00075     while (*c)
00076       ++c;
00077     ++c;
00078   }
00079 }
00080 
00081 
00082 BroadcastArg::~BroadcastArg()
00083 {
00084   delete[] m_argv[0];
00085   delete[] m_argv;
00086 }
00087 
00088 } // namespace stk
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines