Ejemplo n.º 1
0
int
Mutex_Acquire_Release_Test::svc ()
{
#if ACE_DEBUG_CST > 0
  ACE_hthread_t thread_id;
  ACE_Thread_Manager::instance ()->thr_self (thread_id);

  ACE_DEBUG ((LM_DEBUG,
              "Mutex_Acquire_Release_Test::svc (), thread ID is %d\n",
              thread_id));
#endif /* ACE_DEBUG_CST */

  timer_.start ();

  for (ACE_UINT32 i = 0; i < iterations_; ++i)
    {
      // Block on the mutex.
      ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1);

      // Release the mutex so that the low priority thread can
      // proceed.  The ACE_GUARD_RETURN macro implicity releases the
      // mutex.
    }

  timer_.stop ();
  timer_.elapsed_time (elapsed_time_); /* nanoseconds */

#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Mutex_Acquire_Release_Test::svc, finishing\n"));
#endif /* ACE_DEBUG_CST */

  return 0;
}
Ejemplo n.º 2
0
int
Suspend_Resume_Test::svc ()
{
#if ACE_DEBUG_CST > 0
  ACE_hthread_t thread_id;
  ACE_Thread_Manager::instance ()->thr_self (thread_id);

  ACE_DEBUG ((LM_DEBUG, "Suspend_Resume_Test::svc (), thread ID is %d\n",
              thread_id));
#endif /* ACE_DEBUG_CST */

  low_.ready ();

  // For information:  the cost of the just the loop itself below,
  // without the suspend and resume calls, on a 166 MHz Ultrasparc
  // is about 12.3 nanoseconds per iteration.

  timer_.start ();

  for (ACE_UINT32 i = 0; i < iterations_; ++i)
    {
#if ACE_DEBUG_CST > 0
      if (i % (iterations_ >= 10  ?  iterations_ / 10  :  1) ==  0)
        ACE_DEBUG ((LM_DEBUG, "Suspend_Resume_Test::svc (), iteration %u\n",
                    i));
#endif /* ACE_DEBUG_CST */

      if (ACE_OS::thr_suspend (low_.thread_id ()) != 0)
        {
          ACE_ERROR ((LM_ERROR, "%p\n", "thr_suspend"));
          low_.done ();
          return -1;
        }

      if (ACE_OS::thr_continue (low_.thread_id ()) != 0  &&
          errno != EINVAL)
        // EINVAL is OK:  it just means that the thread needs to be joined.
        {
          ACE_ERROR ((LM_ERROR, "%p\n", "thr_continue"));
          low_.done ();
          return -1;
        }
    }

  timer_.stop ();
  timer_.elapsed_microseconds (elapsed_time_);

  low_.done ();

#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Suspend_Resume_Test::svc, finishing\n"));
#endif /* ACE_DEBUG_CST */

  return 0;
}
Ejemplo n.º 3
0
void seqstrseq_time_test (CORBA::ULong num_seq_loops,
                          CORBA::ULong num_string_loops,
                          bool use_long_str)
{
  ACE_High_Res_Timer timer;
  ACE_hrtime_t time;

  CORBA::ULong sss_len;
  CORBA::ULong str_len;

  Sequence_Str_Sequences seqs;
  seqs.seq_str_seq.length(0);

  // start timing
  timer.start();

  for (CORBA::ULong seq_idx = 0; seq_idx < num_seq_loops; ++seq_idx)
  {
    sss_len = seqs.seq_str_seq.length();
    seqs.seq_str_seq.length(sss_len + 1);
    Str_Sequences & strs = seqs.seq_str_seq[sss_len];
    //strs.first_str.length(0);
    for (CORBA::ULong str_idx = 0; str_idx < num_string_loops; ++str_idx)
    {
      str_len = strs.second_str.length();
      strs.second_str.length(str_len + 1);
      strs.second_str[str_len] = use_long_str ? long_str : short_str;
    }
  }
  // end timing
  timer.stop();
  timer.elapsed_time(time);

  if (use_csv)
    {
      ACE_DEBUG((LM_INFO,
                 ACE_TEXT("2, 0, %u, %u, %s, %Q\n"),
                 num_string_loops,
                 num_seq_loops,
                 use_long_str ? ACE_TEXT("long"): ACE_TEXT("short"),
                 time ));
    }
  else
    {
      ACE_DEBUG((LM_INFO,
                 ACE_TEXT("Sequence of string seq (%u, %u, %s) = %Q ns\n"),
                 num_string_loops,
                 num_seq_loops,
                 use_long_str ? ACE_TEXT("long"): ACE_TEXT("short"),
                 time ));
    }
}
Ejemplo n.º 4
0
Archivo: MIF.cpp Proyecto: esohns/ATCD
int MyTask::svc (void)
{
  ACE_hthread_t thr_handle;
  ACE_Thread::self (thr_handle);

  ACE_DEBUG ((LM_DEBUG, "(%t|%T): task activated\n"));
  ACE_ASSERT (dispatcher_ != 0);

  (void) dispatcher_->schedule (guid_, qos_);

  barrier_.wait ();

  long prime_number = 9619899;

  ACE_High_Res_Timer timer;
  ACE_Time_Value elapsed_time;
  ACE_Time_Value seconds_tracker(0,0);

  ACE_Time_Value one_second (1,0);
  ACE_Time_Value compute_count_down_time (exec_duration_, 0);
  ACE_Countdown_Time compute_count_down (&compute_count_down_time);

  timer.start ();
  while (compute_count_down_time > ACE_Time_Value::zero)
    {
      ACE::is_prime (prime_number,
                     2,
                     prime_number / 2);

      compute_count_down.update ();
      timer.stop ();
      timer.elapsed_time (elapsed_time);
      seconds_tracker += elapsed_time;
      if (seconds_tracker >= one_second)
      {
        seconds_tracker.set (0,0);
        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("(%t) Currently running guid=%d")
                    ACE_TEXT (", qos_.importance=%d\n"),
                    guid_, qos_.importance_));
      }
      timer.reset ();
      timer.start ();
    }

  dispatcher_->cancel_schedule (this->guid_);
  return 0;
}
Ejemplo n.º 5
0
static int
speed_test (ACE_UINT32 loops)
{
  double tt    = 0.0,
    ut    = 0.0,
    utus  = 0.0,
    speed = 0.0;

  ACE_Time_Value tc;
  void *ptr = 0;
  ACE_UINT32 i = loops;
  size_t n_chunks = 10;
  size_t chunk_size = 8;

  ACE_DEBUG ((LM_INFO,
              ACE_TEXT (" (%t) ACE_Dynamic_Cached_Allocator ")
              ACE_TEXT ("speed test...\n")));

  DYNAMIC_ALLOCATOR allocator (n_chunks, chunk_size);

  ACE_High_Res_Timer timer;
  timer.reset ();

  timer.start ();

  while (i--)
    {
      ptr = allocator.malloc (chunk_size);
      allocator.free (ptr);
    }

  timer.stop ();

  timer.elapsed_time (tc);

  ACE_DEBUG ((LM_INFO, ACE_TEXT (" (%t) Iterations : %d\n"), loops));
  tt    = tc.sec () + tc.usec ()*1.0e-6;
  ut    = tt/loops;
  utus  = ut*1.0e6;
  speed = loops/tt;

  ACE_DEBUG ((LM_INFO, ACE_TEXT (" (%t) Total time : %.6g [s]\n"), tt));
  ACE_DEBUG ((LM_INFO, ACE_TEXT (" (%t) Unit time  : %.6g [us]\n"), utus));
  ACE_DEBUG ((LM_INFO, ACE_TEXT (" (%t) Speed      : %.6g [1/s]\n"), speed));

  return 0;
}
Ejemplo n.º 6
0
int
Synchronisers::end_synchronization (void)
{
  // Hold the lock and increment the global variable to indicate
  // number of ready threads
  {
    ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->mutex_, -1);

    ready_threads ++;

    if (ready_threads == (number_of_workers + io_threads))
      {
        // Reset the ready_threads so that we can wait at the end of
        // runs
        ready_threads = 0;

        // Start the timer
        test_timer.stop ();

        // Signal all the threads
        this->event_.signal ();

        if (debug)
          {
            ACE_DEBUG ((LM_DEBUG,
                        "(%P|%t) Ended peacefully \n"));
          }

        // return to do our work;
        return 0;
      }


    // If we are not the last thread, let go off the lock
  }

  if (debug)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t) Going to wait .. \n"));
    }

  // Wait blisfully till we are woken up
  this->event_.wait ();

  return 0;
}
Ejemplo n.º 7
0
static
ACE_Time_Value
time_interval (const ACE_Time_Value &interval,
               ACE_hrtime_t& nanoseconds,
               ACE_hrtime_t& microseconds)
{
  ACE_High_Res_Timer timer;

  timer.start ();
  ACE_OS::sleep (interval);
  timer.stop ();

  ACE_Time_Value measured;
  timer.elapsed_time (measured);
  timer.elapsed_time (nanoseconds);
  timer.elapsed_microseconds (microseconds);
  return measured;
}
Ejemplo n.º 8
0
int
ACE_TMAIN (int argc_in,
           ACE_TCHAR** argv_in)
{
  RPG_TRACE (ACE_TEXT ("::main"));

  std::string configuration_path =
    RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                                                          true);
  std::string data_path =
    RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                                                          false);
#if defined (DEBUG_DEBUGGER)
  configuration_path = Common_File_Tools::getWorkingDirectory ();
  data_path = Common_File_Tools::getWorkingDirectory ();
#endif

  // step1: init
  // step1a set defaults
  bool debug_scanner          = MAP_PARSER_DEF_DEBUG_SCANNER;
  bool debug_parser           = MAP_PARSER_DEF_DEBUG_PARSER;
  std::string map_file        = data_path;
  map_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#if defined (DEBUG_DEBUGGER)
  map_file += (MAP_GENERATOR_DEF_LEVEL ? RPG_Common_Tools::sanitize (ACE_TEXT_ALWAYS_CHAR ("engine"))
                                       : ACE_TEXT_ALWAYS_CHAR ("map"));
  map_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
  map_file += ACE_TEXT_ALWAYS_CHAR ("data");
  map_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#else
  map_file += ACE_TEXT_ALWAYS_CHAR(RPG_MAP_DEF_MAPS_SUB);
  map_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#endif
  map_file += (MAP_GENERATOR_DEF_LEVEL ? RPG_Common_Tools::sanitize (ACE_TEXT_ALWAYS_CHAR (RPG_ENGINE_LEVEL_DEF_NAME))
                                       : ACE_TEXT_ALWAYS_CHAR (RPG_MAP_DEF_MAP_FILE));
  map_file += (MAP_GENERATOR_DEF_LEVEL ? ACE_TEXT_ALWAYS_CHAR (RPG_ENGINE_LEVEL_FILE_EXT)
                                       : ACE_TEXT_ALWAYS_CHAR (RPG_MAP_FILE_EXT));

  std::string schema_directory = configuration_path;
#if defined (DEBUG_DEBUGGER)
  schema_directory = Common_File_Tools::getWorkingDirectory ();
  schema_directory += ACE_DIRECTORY_SEPARATOR_CHAR_A;
  schema_directory += ACE_TEXT_ALWAYS_CHAR ("engine");
#endif

  bool trace_information      = false;
  bool print_version_and_exit = false;

  // step1ba: parse/process/validate configuration
  if (!do_processArguments (argc_in,
                            argv_in,
                            debug_scanner,
                            debug_parser,
                            map_file,
                            trace_information,
                            print_version_and_exit))
  {
    // make 'em learn...
    do_printUsage (ACE::basename (argv_in[0]));

    // clean up
    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step1bb: validate arguments
  if (!Common_File_Tools::isReadable (map_file) ||
      !Common_File_Tools::isDirectory (schema_directory))
  {
    // make 'em learn...
    do_printUsage (ACE::basename (argv_in[0]));

    // clean up
    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step1c: initialize logging and/or tracing
  std::string log_file;
  if (!Common_Tools::initializeLogging (ACE::basename (argv_in[0]),   // program name
                                        log_file,                    // logfile
                                        false,                       // log to syslog ?
                                        false,                       // trace messages ?
                                        trace_information,           // debug messages ?
                                        NULL))                       // logger
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to Common_Tools::initializeLogging(), aborting\n")));

    // clean up
    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step1d: handle specific program modes
  if (print_version_and_exit)
  {
    do_printVersion (ACE::basename (argv_in[0]));

    // clean up
    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_SUCCESS;
  } // end IF

  ACE_High_Res_Timer timer;
  timer.start ();
  // step2: do actual work
  do_work (schema_directory,
           debug_scanner,
           debug_parser,
           map_file);
  timer.stop ();

  // debug info
  std::string working_time_string;
  ACE_Time_Value working_time;
  timer.elapsed_time (working_time);
  RPG_Common_Tools::period2String (working_time,
                                   working_time_string);
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("total working time (h:m:s.us): \"%s\"...\n"),
              ACE_TEXT (working_time_string.c_str ())));

  // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
  if (ACE::fini () == -1)
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

  return EXIT_SUCCESS;
}
Ejemplo n.º 9
0
CORBA::Long
Simple_Server_i::test_method (CORBA::Long exec_duration)
{
  ACE_hthread_t thr_handle;
  ACE_Thread::self (thr_handle);
  int prio;
  int guid;
  RTScheduling::Current::IdType_var id = this->current_->id ();

  ACE_OS::memcpy (&guid,
                  id->get_buffer (),
                  sizeof (id->length ()));

  ACE_High_Res_Timer timer;
  ACE_Time_Value elapsed_time;

  ACE_DEBUG ((LM_DEBUG, "Request in thread %t\n"));

  if (ACE_Thread::getprio (thr_handle, prio) == -1)
    {
      if (errno == ENOTSUP)
        {
          ACE_DEBUG((LM_DEBUG,
                     ACE_TEXT ("getprio not supported on this platform\n")));
          return 0;
        }

      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("%p\n"),
                         ACE_TEXT ("getprio failed")),
                        -1);
    }

  ACE_DEBUG ((LM_DEBUG,
              "Request in thread %t, prio = %d,"
              "exec duration = %u\n", prio, exec_duration));

  static CORBA::ULong prime_number = 9619899;

  ACE_Time_Value compute_count_down_time (exec_duration, 0);
  ACE_Countdown_Time compute_count_down (&compute_count_down_time);

  //Applicable only for CV based implementations
  //yield every 1 sec
  ACE_Time_Value yield_interval (1,0);

  ACE_Time_Value yield_count_down_time (yield_interval);
  ACE_Countdown_Time yield_count_down (&yield_count_down_time);

  timer.start ();
  int j=0;
  while (compute_count_down_time > ACE_Time_Value::zero)
    {
      ACE::is_prime (prime_number,
                     2,
                     prime_number / 2);

      ++j;

#ifdef KOKYU_DSRT_LOGGING
      if (j%1000 == 0)
        {
          ACE_DEBUG ((LM_DEBUG,
            "(%t|%T) loop # = %d, load = %usec\n", j, exec_duration));
        }
#endif
      if (j%1000 == 0)
        {
          ACE_Time_Value run_time = ACE_OS::gettimeofday ();
          task_stats_.sample (ACE_UINT32 (run_time.msec ()), guid);
        }

      compute_count_down.update ();

      if (enable_yield_)
        {
          yield_count_down.update ();
          if (yield_count_down_time <= ACE_Time_Value::zero)
            {
              CORBA::Policy_var sched_param_policy =
                current_->scheduling_parameter();

              const char * name = 0;

              CORBA::Policy_ptr implicit_sched_param = 0;
              current_->update_scheduling_segment (name,
                                                   sched_param_policy.in (),
                                                   implicit_sched_param);
              yield_count_down_time = yield_interval;
              yield_count_down.start ();
            }
        }
    }

  timer.stop ();
  timer.elapsed_time (elapsed_time);

  ACE_DEBUG ((LM_DEBUG,
              "Request processing in thread %t done, "
              "prio = %d, load = %d, elapsed time = %umsec\n",
              prio, exec_duration, elapsed_time.msec () ));

  return exec_duration;
}
Ejemplo n.º 10
0
int
ACE_TMAIN (int argc_in,
           ACE_TCHAR* argv_in[])
{
  RPG_TRACE (ACE_TEXT ("::main"));

  // *PORTABILITY*: on Windows, need to init ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
  if (ACE::init () == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE::init(): \"%m\", aborting\n")));
    return EXIT_FAILURE;
  } // end IF
#endif

  std::string data_path =
    RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                                                          false);
#if defined (DEBUG_DEBUGGER)
  data_path = Common_File_Tools::getWorkingDirectory ();
#endif

  // step1: init
  // step1a set defaults
  RPG_Map_FloorPlan_Configuration_t configuration;
  configuration.corridors              = MAP_GENERATOR_DEF_CORRIDORS;
  configuration.doors                  = MAP_GENERATOR_DEF_DOORS;
  configuration.map_size_x             = MAP_GENERATOR_DEF_DIMENSION_X;
  configuration.map_size_y             = MAP_GENERATOR_DEF_DIMENSION_Y;
  configuration.max_num_doors_per_room = MAP_GENERATOR_DEF_MAX_NUMDOORS_PER_ROOM;
  configuration.maximize_rooms         = MAP_GENERATOR_DEF_MAXIMIZE_ROOMSIZE;
  configuration.min_room_size          = MAP_GENERATOR_DEF_MIN_ROOMSIZE;
  configuration.num_areas              = MAP_GENERATOR_DEF_NUM_AREAS;
  configuration.square_rooms           = MAP_GENERATOR_DEF_SQUARE_ROOMS;

  bool generate_level             = MAP_GENERATOR_DEF_LEVEL;

  std::string output_file         = data_path;
  output_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#if defined (DEBUG_DEBUGGER)
  output_file += ACE_TEXT_ALWAYS_CHAR("map");
  output_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
  output_file += ACE_TEXT_ALWAYS_CHAR("data");
  output_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#else
  output_file += ACE_TEXT_ALWAYS_CHAR(RPG_MAP_MAPS_SUB);
  output_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#endif
  std::string default_output_file = output_file;
  default_output_file +=
      (MAP_GENERATOR_DEF_LEVEL ? RPG_Common_Tools::sanitize(ACE_TEXT_ALWAYS_CHAR(RPG_ENGINE_LEVEL_DEF_NAME))
                               : ACE_TEXT_ALWAYS_CHAR(RPG_MAP_DEF_MAP_FILE));
  default_output_file +=
      (MAP_GENERATOR_DEF_LEVEL ? ACE_TEXT_ALWAYS_CHAR(RPG_ENGINE_LEVEL_FILE_EXT)
                               : ACE_TEXT_ALWAYS_CHAR(RPG_MAP_FILE_EXT));
  output_file = default_output_file;

  bool dump_result                = MAP_GENERATOR_DEF_DUMP;
  bool trace_information          = false;
  bool print_version_and_exit     = false;
  bool random                     = false;

  // step1ba: parse/process/validate configuration
  Map_Generator_Options_t set_options;
  if (!do_processArguments(argc_in,
                           argv_in,
                           configuration.min_room_size,
                           configuration.corridors,
                           configuration.max_num_doors_per_room,
                           generate_level,
                           configuration.maximize_rooms,
                           output_file,
                           dump_result,
                           configuration.num_areas,
                           configuration.square_rooms,
                           trace_information,
                           print_version_and_exit,
                           configuration.map_size_x,
                           configuration.map_size_y,
                           random,
                           set_options))
  {
    // make 'em learn...
    do_printUsage(std::string(ACE::basename(argv_in[0])));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF
  if (random)
  {
    Map_Generator_OptionsIterator_t iterator = set_options.find('a');
    if (iterator == set_options.end())
      configuration.min_room_size = 0;
//    iterator = set_options.find('c');
//    if (iterator == set_options.end())
//      configuration.corridors = false;
    iterator = set_options.find('d');
    if (iterator == set_options.end())
      configuration.max_num_doors_per_room = 0;
//    iterator = set_options.find('m');
//    if (iterator == set_options.end())
//      configuration.maximize_rooms = false;
    iterator = set_options.find('r');
    if (iterator == set_options.end())
      configuration.num_areas = 0;
//    iterator = set_options.find('s');
//    if (iterator == set_options.end())
//      configuration.square_rooms = false;
    iterator = set_options.find('x');
    if (iterator == set_options.end())
      configuration.map_size_x = 0;
    iterator = set_options.find('y');
    if (iterator == set_options.end())
      configuration.map_size_y = 0;
  } // end IF

  // step1bb: validate arguments
  if ((!random &&
       ((configuration.num_areas == 0)  ||
        (configuration.map_size_x == 0) ||
        (configuration.map_size_y == 0)))         ||
      (configuration.max_num_doors_per_room == 1) || // cannot enforce this (yet: *TODO*)
      (configuration.corridors &&
       !configuration.doors))                        // cannot have corridors without doors...
  {
    ACE_DEBUG((LM_DEBUG,
               ACE_TEXT("invalid argument(s), aborting\n")));

    // make 'em learn...
    do_printUsage(std::string(ACE::basename(argv_in[0])));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step1c: initialize logging and/or tracing
  std::string log_file;
  if (!Common_Tools::initializeLogging (ACE::basename (argv_in[0]),   // program name
                                        log_file,                    // logfile
                                        false,                       // log to syslog ?
                                        false,                       // trace messages ?
                                        trace_information,           // debug messages ?
                                        NULL))                       // logger
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to Common_Tools::initializeLogging(), aborting\n")));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step1d: handle specific program modes
  if (print_version_and_exit)
  {
    do_printVersion(std::string(ACE::basename(argv_in[0])));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_SUCCESS;
  } // end IF

  ACE_High_Res_Timer timer;
  timer.start();

  // step2: do actual work
  do_work(configuration,
          generate_level,
          output_file,
          dump_result,
          random);

  timer.stop();

  // debug info
  std::string working_time_string;
  ACE_Time_Value working_time;
  timer.elapsed_time(working_time);
  RPG_Common_Tools::period2String(working_time,
                                  working_time_string);

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("total working time (h:m:s.us): \"%s\"...\n"),
             ACE_TEXT(working_time_string.c_str())));

  // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
  if (ACE::fini () == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE::fini(): \"%m\", aborting\n")));
    return EXIT_FAILURE;
  } // end IF
#endif

  return EXIT_SUCCESS;
} // end main
Ejemplo n.º 11
0
int main(int argc, char** argv)
{
    char map_magic[16];
    int thisBuild = getBuildNumber();
    int iCoreNumber = getCoreNumberFromBuild(thisBuild);
    showBanner("Movement Map Generator", iCoreNumber);
    setMapMagicVersion(iCoreNumber, map_magic);
    showWebsiteBanner();

    int mapnum = -1;
    float maxAngle = 60.0f;
    int tileX = -1, tileY = -1;
    bool skipLiquid = false,
         skipContinents = false,
         skipJunkMaps = true,
         skipBattlegrounds = false,
         debugOutput = false,
         silent = false,
         bigBaseUnit = false;
    int num_threads = 0;
    char* offMeshInputPath = NULL;

    bool validParam = handleArgs(argc, argv, mapnum,
                                 tileX, tileY, maxAngle,
                                 skipLiquid, skipContinents, skipJunkMaps, skipBattlegrounds,
                                 debugOutput, silent, bigBaseUnit, num_threads, offMeshInputPath);

    if (!validParam)
        { return silent ? -1 : finish(" You have specified invalid parameters (use -h for more help)", -1); }

    if (mapnum == -1 && debugOutput)
    {
        if (silent)
            { return -2; }

        printf(" You have specifed debug output, but didn't specify a map to generate.\n");
        printf(" This will generate debug output for ALL maps.\n");
        printf(" Are you sure you want to continue? (y/n) ");
        if (getchar() != 'y')
            { return 0; }
    }

    if (!checkDirectories(debugOutput))
        { return silent ? -3 : finish(" Press any key to close...", -3); }

    MapBuilder builder(map_magic, maxAngle, skipLiquid, skipContinents, skipJunkMaps,
                       skipBattlegrounds, debugOutput, bigBaseUnit, offMeshInputPath);

    ACE_Time_Value elapsed;
    ACE_High_Res_Timer timer;
    
    timer.start();
    if (tileX > -1 && tileY > -1 && mapnum >= 0)
        { builder.buildSingleTile(mapnum, tileX, tileY); }
    else 
    {
        if (num_threads && builder.activate(num_threads)== -1)
        {
            if (!silent)
              { printf(" Thread initialization was not ok. The build is single threaded\n"); }
        }

        if (builder.activated())
          { printf(" Using %d thread(s) for building\n", num_threads);}

        if (mapnum >= 0)
          { builder.buildMap(uint32(mapnum), true); }
        else
          { builder.buildAllMaps(); }
    }
    timer.stop();
    timer.elapsed_time(elapsed);
    printf(" \n Total build time: %ld seconds\n\n", elapsed.sec());
    
    return silent ? 1 : finish(" Movemap build is complete! Press enter to exit\n", 1);
}
Ejemplo n.º 12
0
int
Client::svc (void)
{
  try
    {
      Octet_Seq octetSeq(SIZE_BLOCK);
      Char_Seq charSeq(SIZE_BLOCK);
      ACE_High_Res_Timer timer;
      ACE_OS::printf("Start sending %d Msgs...\n",this->niterations_);

      charSeq.length(SIZE_BLOCK);
      octetSeq.length(SIZE_BLOCK);

      // This sets up the connector, so that we do not incur
      // the overhead on the first call in the loop.
      server_->sendCharSeq (charSeq);

      timer.start ();

      ACE_UINT32 client_count = 0;
      for (ACE_UINT32 i = 0; i < this->niterations_; ++i)
        {
          client_count++;

          server_->sendCharSeq (charSeq);

          //server_->sendOctetSeq (octetSeq);

          //ACE_DEBUG ((LM_DEBUG, "."));
        }
      timer.stop ();

      ACE_Time_Value measured;
      timer.elapsed_time (measured);

      //ACE_DEBUG ((LM_DEBUG, "...finished\n"));

      time_t dur = measured.sec () * 1000000 + measured.usec ();
      if (dur == 0 || this->niterations_ == 0)
        ACE_DEBUG ((LM_DEBUG, "Time not measurable, calculation skipped\n"));
      else
      {
        ACE_DEBUG ((LM_DEBUG,
                    "Time for %u Msgs: %u usec\n",
                    this->niterations_,
                    dur));

        ACE_DEBUG ((LM_DEBUG, "Time for 1 Msg: %u usec, %u calls/sec\n",
                    dur / this->niterations_,
                    1000000 / (dur / this->niterations_)));
      }

      for (int c = 0; c < 10; ++c)
        server_->shutdown ();

    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("MT_Client: exception raised");
    }
  return 0;
}
Ejemplo n.º 13
0
int
ACE_TMAIN (int argc_in,
           ACE_TCHAR* argv_in[])
{
  RPG_TRACE (ACE_TEXT ("::main"));

  // *PROCESS PROFILE*
  ACE_Profile_Timer process_profile;
  // start profile timer...
  process_profile.start ();

  // step1: initialize
//  // *PORTABILITY*: on Windows, init ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//  if (ACE::init () == -1)
//  {
//    ACE_DEBUG ((LM_ERROR,
//                ACE_TEXT ("failed to ACE::init(): \"%m\", aborting\n")));
//    return EXIT_FAILURE;
//  } // end IF
//#endif

  // step1 init/validate configuration

  // step1a: process commandline arguments
  std::string configuration_path =
    RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                                                          true);
#if defined (DEBUG_DEBUGGER)
  configuration_path = Common_File_Tools::getWorkingDirectory ();
#endif // #ifdef DEBUG_DEBUGGER

  std::string configuration_file = configuration_path;
  configuration_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#if defined (DEBUG_DEBUGGER)
  configuration_file += ACE_TEXT_ALWAYS_CHAR ("protocol");
  configuration_file += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#endif
  configuration_file += ACE_TEXT_ALWAYS_CHAR (IRC_CLIENT_CNF_DEF_INI_FILE);

  bool debug_parser                    = false;
  bool log_to_file                     = false;
  bool trace_information               = false;
  bool print_version_and_exit          = false;
  unsigned int num_thread_pool_threads = IRC_CLIENT_DEF_NUM_TP_THREADS;
  if (!do_processArguments (argc_in,
                            argv_in,
                            configuration_file,
                            debug_parser,
                            log_to_file,
                            trace_information,
                            print_version_and_exit,
                            num_thread_pool_threads))
  {
    // make 'em learn...
    do_printUsage (ACE::basename (argv_in[0]));

//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF

  // validate argument(s)
  if (!Common_File_Tools::isReadable (configuration_file))
  {
    // make 'em learn...
    do_printUsage (ACE::basename (argv_in[0]));

//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF

  // initialize logging and/or tracing
  std::string log_file;
  if (log_to_file)
    log_file = RPG_Common_File_Tools::getLogFilename (ACE::basename (argv_in[0]));
  if (!Common_Tools::initializeLogging (ACE::basename (argv_in[0]), // program name
                                        log_file,                   // logfile
                                        false,                      // log to syslog ?
                                        false,                      // trace messages ?
                                        trace_information,          // debug messages ?
                                        NULL))                      // logger
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to Common_Tools::initializeLogging(), aborting\n")));

//    // *PORTABILITY*: on Windows, need to fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF

  // handle specific program modes
  if (print_version_and_exit)
  {
    do_printVersion (ACE::basename (argv_in[0]));

    Common_Tools::finalizeLogging ();
//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_SUCCESS;
  } // end IF

  // initialize configuration object
  Stream_AllocatorHeap heap_allocator;
  RPG_Net_Protocol_MessageAllocator message_allocator (RPG_NET_MAXIMUM_NUMBER_OF_INFLIGHT_MESSAGES,
                                                       &heap_allocator);
  RPG_Net_Protocol_Module_IRCHandler_Module IRC_handler_module (std::string ("IRCHandler"),
                                                                NULL);
  RPG_Net_Protocol_Module_IRCHandler* IRC_handler_impl = NULL;
  IRC_handler_impl =
    dynamic_cast<RPG_Net_Protocol_Module_IRCHandler*>(IRC_handler_module.writer ());
  if (!IRC_handler_impl)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("dynamic_cast<RPG_Net_Protocol_Module_IRCHandler> failed, aborting\n")));

    Common_Tools::finalizeLogging ();
//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF
  if (!IRC_handler_impl->initialize (&message_allocator,
                                     RPG_NET_PROTOCOL_BUFFER_SIZE,
                                     true,                         // auto-answer "ping" as a client ?...
                                     true))                        // clients print ('.') dots for received "pings"...
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to initialize module: \"%s\", aborting\n"),
                ACE_TEXT (IRC_handler_module.name ())));

    Common_Tools::finalizeLogging ();
//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF

  RPG_Net_Protocol_Configuration configuration;
  // ************ socket configuration data ************
  configuration.socketConfiguration.bufferSize =
      RPG_NET_DEFAULT_SOCKET_RECEIVE_BUFFER_SIZE;

  // ************ stream configuration data ****************
  configuration.streamConfiguration.messageAllocator = &message_allocator;
  configuration.streamConfiguration.bufferSize = RPG_NET_PROTOCOL_BUFFER_SIZE;
  configuration.streamConfiguration.module = &IRC_handler_module;
  configuration.streamConfiguration.statisticReportingInterval = 0; // == off

  // ************ protocol configuration data **************
  configuration.protocolConfiguration.streamConfiguration.crunchMessageBuffers =
    RPG_NET_PROTOCOL_DEF_CRUNCH_MESSAGES;
  configuration.protocolConfiguration.streamConfiguration.debugScanner =
   debug_parser;
  configuration.protocolConfiguration.streamConfiguration.debugParser =
   debug_parser;
  configuration.protocolConfiguration.clientPingInterval = 0; // servers only
  configuration.protocolConfiguration.loginOptions.nick =
   IRC_CLIENT_DEF_IRC_NICK;
  std::string hostname;
  Net_Common_Tools::retrieveLocalHostname (hostname);
  if (IRC_CLIENT_CNF_IRC_USERMSG_TRADITIONAL)
  {
    configuration.protocolConfiguration.loginOptions.user.hostname.discriminator =
      RPG_Net_Protocol_IRCLoginOptions::User::Hostname::STRING;
    configuration.protocolConfiguration.loginOptions.user.hostname.string = &hostname;
  } // end IF
  else
  {
    configuration.protocolConfiguration.loginOptions.user.hostname.discriminator =
      RPG_Net_Protocol_IRCLoginOptions::User::Hostname::BITMASK;
    // *NOTE*: hybrid-7.2.3 seems to have a bug: 4 --> +i
    configuration.protocolConfiguration.loginOptions.user.hostname.mode =
      IRC_CLIENT_DEF_IRC_USERMODE;
  } // end ELSE
  configuration.protocolConfiguration.loginOptions.user.servername =
    ACE_TEXT_ALWAYS_CHAR (RPG_NET_PROTOCOL_DEF_IRC_SERVERNAME);
  configuration.protocolConfiguration.loginOptions.channel =
    ACE_TEXT_ALWAYS_CHAR (IRC_CLIENT_DEF_IRC_CHANNEL);
  // populate user/realname
  Common_Tools::getCurrentUserName (configuration.protocolConfiguration.loginOptions.user.username,
                                    configuration.protocolConfiguration.loginOptions.user.realname);

  // step1db: parse config file (if any)
  std::string serverHostname      = ACE_TEXT_ALWAYS_CHAR(IRC_CLIENT_DEF_SERVER_HOSTNAME);
  unsigned short serverPortNumber = IRC_CLIENT_DEF_SERVER_PORT;
  if (!configuration_file.empty ())
    do_parseConfigurationFile (configuration_file,
                               configuration.protocolConfiguration.loginOptions,
                               serverHostname,
                               serverPortNumber);

  ACE_High_Res_Timer timer;
  timer.start();
  // step2: do actual work
  do_work (configuration,
           serverHostname,
           serverPortNumber,
           num_thread_pool_threads);
  // clean up
  IRC_handler_module.close ();
  timer.stop ();

  // debug info
  std::string working_time_string;
  ACE_Time_Value working_time;
  timer.elapsed_time (working_time);
  Common_Tools::period2String (working_time,
                               working_time_string);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("total working time (h:m:s.us): \"%s\"...\n"),
              ACE_TEXT (working_time_string.c_str ())));

  // stop profile timer...
  process_profile.stop ();

  // only process profile left to do...
  ACE_Profile_Timer::ACE_Elapsed_Time elapsed_time;
  elapsed_time.real_time = 0.0;
  elapsed_time.user_time = 0.0;
  elapsed_time.system_time = 0.0;
  if (process_profile.elapsed_time (elapsed_time) == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE_Profile_Timer::elapsed_time: \"%m\", aborting\n")));

    Common_Tools::finalizeLogging ();
//    // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//    if (ACE::fini () == -1)
//      ACE_DEBUG ((LM_ERROR,
//                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

    return EXIT_FAILURE;
  } // end IF
  ACE_Profile_Timer::Rusage elapsed_rusage;
  ACE_OS::memset (&elapsed_rusage, 0, sizeof (ACE_Profile_Timer::Rusage));
  process_profile.elapsed_rusage(elapsed_rusage);
  ACE_Time_Value user_time(elapsed_rusage.ru_utime);
  ACE_Time_Value system_time(elapsed_rusage.ru_stime);
  std::string user_time_string;
  std::string system_time_string;
  Common_Tools::period2String (user_time,
                               user_time_string);
  Common_Tools::period2String (system_time,
                               system_time_string);

  // debug info
#if !defined (ACE_WIN32) && !defined (ACE_WIN64)
  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT(" --> Process Profile <--\nreal time = %A seconds\nuser time = %A seconds\nsystem time = %A seconds\n --> Resource Usage <--\nuser time used: %s\nsystem time used: %s\nmaximum resident set size = %d\nintegral shared memory size = %d\nintegral unshared data size = %d\nintegral unshared stack size = %d\npage reclaims = %d\npage faults = %d\nswaps = %d\nblock input operations = %d\nblock output operations = %d\nmessages sent = %d\nmessages received = %d\nsignals received = %d\nvoluntary context switches = %d\ninvoluntary context switches = %d\n"),
             elapsed_time.real_time,
             elapsed_time.user_time,
             elapsed_time.system_time,
             user_time_string.c_str(),
             system_time_string.c_str(),
             elapsed_rusage.ru_maxrss,
             elapsed_rusage.ru_ixrss,
             elapsed_rusage.ru_idrss,
             elapsed_rusage.ru_isrss,
             elapsed_rusage.ru_minflt,
             elapsed_rusage.ru_majflt,
             elapsed_rusage.ru_nswap,
             elapsed_rusage.ru_inblock,
             elapsed_rusage.ru_oublock,
             elapsed_rusage.ru_msgsnd,
             elapsed_rusage.ru_msgrcv,
             elapsed_rusage.ru_nsignals,
             elapsed_rusage.ru_nvcsw,
             elapsed_rusage.ru_nivcsw));
#else
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT (" --> Process Profile <--\nreal time = %A seconds\nuser time = %A seconds\nsystem time = %A seconds\n --> Resource Usage <--\nuser time used: %s\nsystem time used: %s\n"),
              elapsed_time.real_time,
              elapsed_time.user_time,
              elapsed_time.system_time,
              user_time_string.c_str (),
              system_time_string.c_str ()));
#endif

  Common_Tools::finalizeLogging ();

//  // *PORTABILITY*: on Windows, fini ACE...
//#if defined (ACE_WIN32) || defined (ACE_WIN64)
//  if (ACE::fini () == -1)
//    ACE_DEBUG ((LM_ERROR,
//                ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
//#endif

  return EXIT_SUCCESS;
} // end main
Ejemplo n.º 14
0
int
Ping_Suspend_Resume_Test::svc ()
{
#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test::svc (), entering"));

  ACE_hthread_t thread_id;
  ACE_Thread_Manager::instance ()->thr_self (thread_id);

  ACE_DEBUG ((LM_DEBUG, "; thread ID is %u\n", thread_id));
#endif /* ACE_DEBUG_CST */

  high_.ready ();

#if ACE_DEBUG_CST > 0
  int priority, high_priority;
  ACE_OS::thr_getprio (thread_id, priority);
  ACE_OS::thr_getprio (high_.thread_id (), high_priority);
  ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test::svc (), priority is %d, "
                        ", high thread priority is %d\n",
              priority, high_priority));
#endif /* ACE_DEBUG_CST */

  // For information:  the cost of the just the loop itself below,
  // without the suspend and resume calls, on a 166 MHz Ultrasparc
  // is about 12.3 nanoseconds per iteration.

  timer_.start ();

  ACE_UINT32 i;

  for (i = 0; i < iterations_; ++i)
    {
#if ACE_DEBUG_CST > 0
      if (i % (iterations_ >= 10  ?  iterations_ / 10  :  1) ==  0)
        {
          ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test::svc (), iteration "
                                "%d, continue high-priority thread %u\n",
                      i, high_.thread_id ()));
        }
#endif /* ACE_DEBUG_CST */
      if (ACE_OS::thr_continue (high_.thread_id ()) != 0  &&
          errno != EINVAL)
        // EINVAL is OK:  it just means that the thread needs to be joined.
        {
          ACE_ERROR ((LM_ERROR, "%p\n", "thr_continue"));
          high_.done ();
          return -1;
        }
    }

  timer_.stop ();
  timer_.elapsed_microseconds (elapsed_time_);

  high_.done ();
#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test::svc: told high priority "
                        "task to terminate\n"));
#endif /* ACE_DEBUG_CST */

  // Resume the thread until thr_continue fails, indicating that it has
  // finished.
  for (i = 0; i < 10000  &&  ! ACE_OS::thr_continue (high_.thread_id ());
       ++i) /* null */;

  // Don't count the one iteration that was used to allow the high-priority
  // thread to terminate.
  if (high_.iterations () < iterations_)
    ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test: high priority task "
                "executed only %u iterations!\n",
                high_.iterations ()));

#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Ping_Suspend_Resume_Test::svc, finishing\n"));
#endif /* ACE_DEBUG_CST */

  return 0;
}
Ejemplo n.º 15
0
int
ACE_TMAIN (int argc_in,
           ACE_TCHAR* argv_in[])
{
    RPG_TRACE (ACE_TEXT ("::main"));

    // step0: init ACE
    // *PORTABILITY*: on Windows, init ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::init () == -1)
    {
        ACE_DEBUG ((LM_ERROR,
                    ACE_TEXT ("failed to ACE::init(): \"%m\", aborting\n")));
        return EXIT_FAILURE;
    } // end IF
#endif

    // step1: init
    // step1a set defaults
    std::string configuration_path =
        RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                true);
    std::string data_path =
        RPG_Common_File_Tools::getConfigurationDataDirectory (ACE_TEXT_ALWAYS_CHAR (BASEDIR),
                false);
#if defined (DEBUG_DEBUGGER)
    configuration_path = Common_File_Tools::getWorkingDirectory ();
    data_path = Common_File_Tools::getWorkingDirectory ();
#endif // DEBUG_DEBUGGER

    bool dump_dictionary = false;

    std::string sound_directory = data_path;
    sound_directory += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#if defined (DEBUG_DEBUGGER)
    sound_directory += ACE_TEXT_ALWAYS_CHAR ("sound");
    sound_directory += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    sound_directory += ACE_TEXT_ALWAYS_CHAR (RPG_COMMON_DATA_SUB);
#else
    sound_directory += ACE_TEXT_ALWAYS_CHAR (RPG_SOUND_DATA_SUB);
#endif // DEBUG_DEBUGGER

    bool play_random_sounds = SOUNDPARSER_DEF_PLAY_RANDOM_SOUNDS;

    std::string schema_repository = configuration_path;
#if defined (DEBUG_DEBUGGER)
    schema_repository += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    schema_repository += ACE_TEXT_ALWAYS_CHAR("engine");
#endif // DEBUG_DEBUGGER

    std::string filename = configuration_path;
    filename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#if defined (DEBUG_DEBUGGER)
    filename += ACE_TEXT_ALWAYS_CHAR ("sound");
    filename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
#endif // DEBUG_DEBUGGER
    filename += ACE_TEXT_ALWAYS_CHAR (RPG_SOUND_DICTIONARY_FILE);

    bool trace_information = false;
    bool print_version_and_exit = false;
    bool validate_XML = true;

//  RPG_Sound_SDLConfig_t audio_config;
//  audio_config.frequency = RPG_SOUND_DEF_AUDIO_FREQUENCY;
//  audio_config.format    = RPG_SOUND_DEF_AUDIO_FORMAT;
//  audio_config.channels  = RPG_SOUND_DEF_AUDIO_CHANNELS;
//  audio_config.chunksize = RPG_SOUND_DEF_AUDIO_CHUNKSIZE;

    // step1b: parse/process/validate configuration
    if (!do_processArguments (argc_in,
                              argv_in,
                              dump_dictionary,
                              sound_directory,
                              play_random_sounds,
                              filename,
                              trace_information,
                              print_version_and_exit,
                              validate_XML))
    {
        // make 'em learn...
        do_printUsage (ACE::basename (argv_in[0]));

        // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
        if (ACE::fini () == -1)
            ACE_DEBUG ((LM_ERROR,
                        ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

        return EXIT_FAILURE;
    } // end IF

    // step1b: validate arguments
    if ((play_random_sounds &&
            !Common_File_Tools::isDirectory (sound_directory)) ||
            !Common_File_Tools::isReadable (filename))
    {
        ACE_DEBUG ((LM_ERROR,
                    ACE_TEXT ("invalid argument, aborting\n")));

        // make 'em learn...
        do_printUsage (ACE::basename (argv_in[0]));

        // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
        if (ACE::fini () == -1)
            ACE_DEBUG ((LM_ERROR,
                        ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

        return EXIT_FAILURE;
    } // end IF

    // step1c: initialize logging and/or tracing
    std::string log_file;
    if (!Common_Tools::initializeLogging (ACE::basename (argv_in[0]), // program name
                                          log_file,                  // logfile
                                          false,                     // log to syslog ?
                                          false,                     // trace messages ?
                                          trace_information,         // debug messages ?
                                          NULL))                     // logger
    {
        ACE_DEBUG ((LM_ERROR,
                    ACE_TEXT ("failed to RPG_Common_Tools::initLogging(), aborting\n")));

        // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
        if (ACE::fini () == -1)
            ACE_DEBUG ((LM_ERROR,
                        ACE_TEXT ("failed to ACE::fini(): \"%m\", aborting\n")));
#endif

        return EXIT_FAILURE;
    } // end IF

    // step1d: handle specific program modes
    if (print_version_and_exit)
    {
        do_printVersion (ACE::basename (argv_in[0]));

        return EXIT_SUCCESS;
    } // end IF

    // step2: init SDL
    if (SDL_Init (SDL_INIT_TIMER |
                  SDL_INIT_AUDIO |
                  SDL_INIT_CDROM |
                  SDL_INIT_NOPARACHUTE) == -1) // "...Prevents SDL from catching fatal signals..."
    {
        ACE_DEBUG ((LM_ERROR,
                    ACE_TEXT ("failed to SDL_Init(): \"%s\", aborting\n"),
                    ACE_TEXT (SDL_GetError ())));

        // *PORTABILITY*: on Windows, we must fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
        if (ACE::fini () == -1)
            ACE_DEBUG ((LM_ERROR,
                        ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

        return EXIT_FAILURE;
    } // end IF
    // ***** keyboard setup *****
    // enable Unicode translation
    SDL_EnableUNICODE (1);
    // enable key repeat
    SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY,
                         SDL_DEFAULT_REPEAT_INTERVAL);
//   // ignore keyboard events
//   SDL_EventState(SDL_KEYDOWN, SDL_IGNORE);
//   SDL_EventState(SDL_KEYUP, SDL_IGNORE);

//   // SDL event filter (filter mouse motion events and the like)
//   SDL_SetEventFilter(event_filter_SDL_cb);

    // step3: do actual work
    ACE_High_Res_Timer timer;
    timer.start ();
    do_work (dump_dictionary,
             sound_directory,
             play_random_sounds,
             schema_repository,
             filename,
             validate_XML);
    timer.stop ();
    // debug info
    std::string working_time_string;
    ACE_Time_Value working_time;
    timer.elapsed_time (working_time);
    Common_Tools::period2String (working_time,
                                 working_time_string);
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("total working time (h:m:s.us): \"%s\"...\n"),
                ACE_TEXT (working_time_string.c_str ())));

    // step4a: fini SDL
    SDL_Quit ();

    // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
    {
        ACE_DEBUG ((LM_ERROR,
                    ACE_TEXT ("failed to ACE::fini(): \"%m\", aborting\n")));
        return EXIT_FAILURE;
    } // end IF
#endif

    return EXIT_SUCCESS;
} // end main
Ejemplo n.º 16
0
void
madara::cid::ga_naive (Settings & settings, double duration)
{
  ACE_High_Res_Timer timer;
  ACE_Time_Value max_tv (0, 0);
  ACE_hrtime_t elapsed (0);
  ACE_hrtime_t maximum (0);
  timer.reset ();
  timer.start ();

  max_tv.set (duration);
  maximum = max_tv.sec () * 1000000000;
  maximum += max_tv.usec () * 1000;

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_naive:" \
    " creating an exact copy of the solution vector\n"));
#endif

  // create an exact copy of the solution vector
  Deployment current;
  current.resize (settings.solution.size ());
  std::copy (settings.solution.begin (), settings.solution.end (), 
    current.begin ());

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_naive:" \
    " calculating latency for the solution so far\n"));
#endif

  uint64_t orig_latency = calculate_latency (settings);
  uint64_t new_latency;

  while (maximum > elapsed)
  {
    // generate some candidates for mutating
    unsigned int candidate1 = rand () % settings.solution.size ();
    unsigned int candidate2 = rand () % settings.solution.size ();

#ifdef ENABLE_CID_LOGGING
    MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
      DLINFO "madara::cid::ga_naive:" \
      " initial candidates: %u, %u\n",
      candidate1, candidate2));
#endif

    // loop until we have two different candidates
    while (candidate1 == candidate2)
      candidate1 = rand () % settings.solution.size ();

#ifdef ENABLE_CID_LOGGING
    MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
      DLINFO "madara::cid::ga_naive:" \
      " final candidates: %u, %u\n",
      candidate1, candidate2));
#endif

    // attempt the swap
    std::swap (current[candidate1], current[candidate2]);

    new_latency = calculate_latency (
      settings.network_latencies, settings.target_deployment, current);

    if (new_latency < orig_latency)
    {
  #ifdef ENABLE_CID_LOGGING
      MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
        DLINFO "madara::cid::ga_naive:" \
        " latency improvement: %Q->%Q. Copying solution.\n",
        orig_latency, new_latency));
  #endif

      std::copy (current.begin (), current.end (), settings.solution.begin ());
      orig_latency = new_latency;
    }
    timer.stop ();
    timer.elapsed_time (elapsed);

  }

  for (unsigned int i = 0; i < settings.solution.size (); ++i)
  {
    if (settings.solution_lookup[settings.solution[i]] != i)
      settings.solution_lookup[settings.solution[i]] = i;
  }
}
Ejemplo n.º 17
0
void madara::cid::ga_degree (Settings & settings, double duration)
{
  if (settings.solution.size () < 2)
    return;

  ACE_High_Res_Timer timer;
  ACE_Time_Value max_tv (0, 0);
  ACE_hrtime_t elapsed (0);
  ACE_hrtime_t maximum (0);
  timer.reset ();
  timer.start ();

  max_tv.set (duration);
  maximum = max_tv.sec () * 1000000000;
  maximum += max_tv.usec () * 1000;

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_degree:" \
    " entering main function\n"));
#endif

  // create an exact copy of the solution vector
  Deployment current;
  current.resize (settings.solution.size ());
  std::copy (settings.solution.begin (), settings.solution.end (), 
    current.begin ());

  uint64_t orig_latency = calculate_latency (settings);

  unsigned int num_degreed_nodes = 0;
  Workflow & deployment = settings.target_deployment;
  SummationsMap & averages = settings.network_summations;
  SolutionMap solution_lookup;

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_degree:" \
    " copying initial solution\n"));
#endif

  for (unsigned int i = 0; i < current.size (); ++i)
  {
    solution_lookup[current[i]] = i;
  }

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_degree:" \
    " counting the degreed nodes in the deployment\n"));
#endif

  // count the number of degreed nodes in the deployment.
  for (unsigned int i = 0; i < deployment.size (); ++i)
  {
    if (deployment[i].size () == 0)
      break;

    ++num_degreed_nodes;
  }

#ifdef ENABLE_CID_LOGGING
  MADARA_DEBUG (MADARA_LOG_EVENT_TRACE, (LM_DEBUG, 
    DLINFO "madara::cid::ga_degree:" \
    " Attempting up to %f seconds worth of mutations to find better solution\n",
    duration));
#endif

  while (maximum > elapsed)
  {
    /**
     * 1/5 times, choose a naive solution.
     * 4/5 times, choose to swap someone from the high degreed candidates
     **/
    int tactic = rand () % 5;
    unsigned int candidate1;
    unsigned int candidate2;
    
    if (tactic == 4)
    {
#ifdef ENABLE_CID_LOGGING
      MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
        DLINFO "madara::cid::ga_degree:" \
        " naively choosing candidates\n"));
#endif

      // go with a naive solution
      candidate1 = rand () % settings.solution.size ();
      candidate2 = rand () % settings.solution.size ();

      if (settings.solution.size () > 0)
      {
        // loop until we have two different candidates
        while (candidate1 == candidate2)
          candidate1 = rand () % settings.solution.size ();
      }
    }
    else
    {
#ifdef ENABLE_CID_LOGGING
      MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
        DLINFO "madara::cid::ga_degree:" \
        " choosing degree-informed candidates\n"));
#endif

      unsigned int choice = rand () % num_degreed_nodes;
      // use degree and latency information to form ideal candidates
      candidate1 = deployment[choice][0].first;

      LatencyVector & cur_summations = 
        settings.network_summations[deployment[choice].size ()];
  
      /**
       * the other candidate can be from a range:
       * 0-2 : top num_degreed_nodes
       * 3 : top 10%
       * 4 : top 25%
       **/
      int candidate_type = rand () % 5;
      unsigned int range;
      if (cur_summations.size () < 50)
      {
        range = cur_summations.size () / 10 + 1;
        candidate2 = solution_lookup[cur_summations[rand () % range].first];
      }
      else if (candidate_type <= 2)
      {
        if (num_degreed_nodes < 5)
        {
          range = cur_summations.size () / 20;
        }
        else
        {
          range = num_degreed_nodes;
        }

#ifdef ENABLE_CID_LOGGING
        MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
          DLINFO "madara::cid::ga_degree:" \
          " choosing from top %u candidates\n",
          range));
#endif

        candidate2 = solution_lookup[cur_summations[rand () % range].first];
      }
      else if (candidate_type == 3)
      {
        // choose candidate2 from the top 10%
        range = cur_summations.size () / 10; 

#ifdef ENABLE_CID_LOGGING
        MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
          DLINFO "madara::cid::ga_degree:" \
          " choosing from top %u candidates\n",
          range));
#endif

        candidate2 = solution_lookup[cur_summations[rand () % range].first];
      }
      else
      {
        // choose candidate2 from the top 25%
        range = cur_summations.size () / 4; 

#ifdef ENABLE_CID_LOGGING
        MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
          DLINFO "madara::cid::ga_degree:" \
          " choosing from top %u candidates\n",
          range));
#endif

        candidate2 = solution_lookup[cur_summations[rand () % range].first];
      }

#ifdef ENABLE_CID_LOGGING
      MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
        DLINFO "madara::cid::ga_degree:" \
        " initial candidates: %u, %u\n",
        candidate1, candidate2));
#endif

      // loop until we have two different candidates
      while (range >= 2 && candidate1 == candidate2)
        candidate2 = solution_lookup[cur_summations[rand () % range].first];
    }

#ifdef ENABLE_CID_LOGGING
    MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
      DLINFO "madara::cid::ga_degree:" \
      " final candidates: %u, %u\n",
      candidate1, candidate2));
#endif

    // attempt the swap
    if (candidate1 != candidate2)
    {
      std::swap (current[candidate1], current[candidate2]);
      solution_lookup[current[candidate1]] = candidate1;
      solution_lookup[current[candidate2]] = candidate2;

      uint64_t new_latency = calculate_latency (
        settings.network_latencies, deployment, current);

#ifdef ENABLE_CID_LOGGING
      MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
        DLINFO "madara::cid::ga_degree:" \
        " latency: %Q->%Q\n",
        orig_latency, new_latency));
#endif

      if (new_latency < orig_latency)
      {
#ifdef ENABLE_CID_LOGGING
        MADARA_DEBUG (MADARA_LOG_DETAILED_TRACE, (LM_DEBUG, 
          DLINFO "madara::cid::ga_degree:" \
          " updating solution to current\n",
          orig_latency, new_latency));
#endif

        std::copy (current.begin (), current.end (), settings.solution.begin ());
        for (unsigned int j = 0; j < settings.solution.size (); ++j)
        {
          if (settings.solution_lookup[settings.solution[j]] != j)
            settings.solution_lookup[settings.solution[j]] = j;
        }
        orig_latency = new_latency;
      }
    }
    timer.stop ();
    timer.elapsed_time (elapsed);
  }
}
Ejemplo n.º 18
0
int run_domain_test ()
{
  ::DDS::ReturnCode_t ret;

  // create participant
  ::DDS::DomainParticipant_var new_dp
    = dpf->create_participant(MY_DOMAIN,
                              PARTICIPANT_QOS_DEFAULT,
                              ::DDS::DomainParticipantListener::_nil (),
                              ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  TEST_CHECK (! CORBA::is_nil (new_dp.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (new_dp.in ()))")
    ACE_TEXT("\n")
  ));

  ::DDS::DomainId_t domain_id
    = new_dp->get_domain_id ();

  TEST_CHECK (domain_id == MY_DOMAIN);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(domain_id == MY_DOMAIN)")
    ACE_TEXT("\n")
  ));

  MyTypeSupport_var fts (new MyTypeSupportImpl);

  if (::DDS::RETCODE_OK != fts->register_type(new_dp.in (), MY_TYPE))
    {
      ACE_ERROR ((LM_ERROR,
      ACE_TEXT ("Failed to register the FooTypeSupport.")));
      return 1;
    }

  // lookup existent participant
  ::DDS::DomainParticipant_var looked_dp
    = dpf->lookup_participant(MY_DOMAIN);

  OpenDDS::DCPS::DomainParticipantImpl* new_dp_servant
    = dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(new_dp.in());

  OpenDDS::DCPS::DomainParticipantImpl* looked_dp_servant
    = dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(looked_dp.in ());

  TEST_CHECK (looked_dp_servant == new_dp_servant);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(looked_dp_servant == new_dp_servant)")
    ACE_TEXT("\n")
  ));

  // create topic
  ::DDS::Topic_var new_topic
    = new_dp->create_topic(MY_TOPIC,
                           MY_TYPE,
                           TOPIC_QOS_DEFAULT,
                           ::DDS::TopicListener::_nil (),
                           ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  OpenDDS::DCPS::TopicImpl* new_topic_servant
    = dynamic_cast<OpenDDS::DCPS::TopicImpl*>(new_topic.in ());

  ::DDS::Duration_t timeout;
  timeout.sec = static_cast<long>(find_topic_timeout.sec ());
  timeout.nanosec = find_topic_timeout.usec ();

  // find existent topic
  ::DDS::Topic_var found_topic
    = new_dp->find_topic(MY_TOPIC, timeout);

  ::OpenDDS::DCPS::TopicImpl* found_topic_servant
    = dynamic_cast<OpenDDS::DCPS::TopicImpl*>
    (found_topic.in ());

  TEST_CHECK (new_topic_servant == found_topic_servant);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(new_topic_servant == found_topic_servant)")
    ACE_TEXT("\n")
  ));

  // find existent topicdescription
  ::DDS::TopicDescription_var found_topicdescription
    = new_dp->lookup_topicdescription(MY_TOPIC);

  TEST_CHECK (! CORBA::is_nil (found_topicdescription.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (found_topicdescription.in ()))")
    ACE_TEXT("\n")
  ));

  // widen the topicdescription to topic
  ::DDS::Topic_var widened_topic
    = ::DDS::Topic::_narrow(found_topicdescription.in ());

  TEST_CHECK (! CORBA::is_nil (widened_topic.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (widened_topic.in ()))")
    ACE_TEXT("\n")
  ));

  ACE_ERROR((LM_ERROR,
    "We expect to see an error message from delete_participant\n"));
  ret = dpf->delete_participant(new_dp.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_PRECONDITION_NOT_MET);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_PRECONDITION_NOT_MET)")
    ACE_TEXT("\n")
  ));

  // delete existent topic first time
  ret = new_dp->delete_topic(found_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // delete existent topic second time
  ret = new_dp->delete_topic(new_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // an extra delete existent topic
  ACE_ERROR((LM_ERROR,
    "We expect to see an error message from delete_topic\n"));
  ret = new_dp->delete_topic(new_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_ERROR);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_ERROR)")
    ACE_TEXT("\n")
  ));

  // Look up the topicdescription after the topic is deleted will
  // return nil.
  found_topicdescription
    = new_dp->lookup_topicdescription(MY_TOPIC);

  TEST_CHECK (CORBA::is_nil(found_topicdescription.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(found_topicdescription.in ()))")
    ACE_TEXT("\n")
  ));

  // find a non-existent topic - return nil
  ACE_High_Res_Timer timer;
  ACE_Time_Value elapsedTime(0, 0);
  timer.start ();
  found_topic = new_dp->find_topic(OTHER_TOPIC, timeout);
  timer.stop();
  timer.elapsed_time(elapsedTime);
  ACE_Time_Value tenMillis (0, 10000);
  elapsedTime += tenMillis;
  // some systems can be short by up to 10 milliseconds
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(found_topic.in ()) && elapsedTime.msec() >= find_topic_timeout.msec())")
    ACE_TEXT("\n")
  ));

  // delete the existent participant
  ret = dpf->delete_participant(new_dp.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // lookup the participant after it's deleted - return nil
  looked_dp = dpf->lookup_participant(MY_DOMAIN);

  TEST_CHECK (CORBA::is_nil(looked_dp.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(looked_dp.in ()))")
    ACE_TEXT("\n")
  ));

  return 0;
}
Ejemplo n.º 19
0
int
Yield_Test::svc ()
{
#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Yield_Test::svc (), entering"));

  ACE_hthread_t thread_id;
  ACE_Thread_Manager::instance ()->thr_self (thread_id);

  int priority;
  ACE_OS::thr_getprio (thread_id, priority);

  ACE_DEBUG ((LM_DEBUG, "; thread ID is %u, priority is %u\n", thread_id,
              priority));
#endif /* ACE_DEBUG_CST */

#if defined (VXWORKS)
  // Start the timer, if it hasn't already been started.
  if (! started_)
    {
      // Double-check.
      ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1);

      if (! started_)
        {
          started_ = 1;
          timer_.start ();
        }
    }
#endif /* VXWORKS */

  for (ACE_UINT32 i = 0; i < iterations_; ++i)
    {
#if ACE_DEBUG_CST > 0
      if (i % (iterations_ >= 10  ?  iterations_ / 10  :  1) ==  0)
        {
          ACE_DEBUG ((LM_DEBUG, "Yield_Test::svc () [%u], iteration %u\n",
                      thread_id, i));
        }
#endif /* ACE_DEBUG_CST */

      ACE_OS::thr_yield ();
    }

#if defined (VXWORKS)
  // Stop the timer, if it hasn't already been started.
  if (! stopped_)
    {
      // Maybe it would be better to read the clock before grabbing
      // the mutex.  Then, only apply the clock reading below, instead
      // of reading the clock after grabbing the mutex.

      // Double-check.
      ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1);

      if (! stopped_)
        {
          stopped_ = 1;
          timer_.stop ();
          timer_.elapsed_time (elapsed_time_); /* nanoseconds */
        }
    }
#else  /* ! VXWORKS */
  timer_barrier_.wait ();
#endif /* ! VXWORKS */

#if ACE_DEBUG_CST > 0
  ACE_DEBUG ((LM_DEBUG, "Yield_Test::svc, finishing\n"));
#endif /* ACE_DEBUG_CST */

  return 0;
}
Ejemplo n.º 20
0
void big_time_test (CORBA::ULong num_list_loops,
                    CORBA::ULong num_seq_loops,
                    CORBA::ULong num_string_loops,
                    bool use_long_str)
{
  ACE_High_Res_Timer timer;
  ACE_hrtime_t time;

  Seq_Structs big_list;
  big_list.seq.length(0);

  CORBA::ULong big_len;
  CORBA::ULong red_len;
  CORBA::ULong sss_len;
  CORBA::ULong str_len;

  // start timing
  timer.start();

  for (CORBA::ULong list_idx = 0; list_idx < num_list_loops; ++list_idx)
  {
    big_len = big_list.seq.length();
    big_list.seq.length(big_len + 1);
    Biglist_Struct & list = big_list.seq[big_len];

    for (CORBA::ULong seq_idx = 0; seq_idx < num_seq_loops; ++seq_idx)
    {
      red_len = list.red_seqs.length();
      list.red_seqs.length(red_len + 1);

      Sequence_Str_Sequences & sss = list.red_seqs[red_len];

      sss_len = sss.seq_str_seq.length();
      sss.seq_str_seq.length(sss_len + 1);

      Str_Sequences & strs = sss.seq_str_seq[sss_len];
      for (CORBA::ULong str_idx = 0; str_idx < num_string_loops; ++str_idx)
      {
        str_len = strs.second_str.length();
        strs.second_str.length(str_len + 1);
        strs.second_str[str_len] = use_long_str ? long_str : short_str;

        str_len = list.strs.first_str.length();
        list.strs.first_str.length(str_len + 1);
        list.strs.first_str[str_len] = use_long_str ? long_str : short_str;

      } // end of str loop
    } // end of seq loop

  } // end of list loop
  // end timing
  timer.stop();
  timer.elapsed_time(time);

  if (use_csv)
    {
      ACE_DEBUG((LM_INFO,
                 ACE_TEXT("3, %u, %u, %u, %s, %Q\n"),
                 num_list_loops,
                 num_string_loops,
                 num_seq_loops,
                 use_long_str ? ACE_TEXT("long"): ACE_TEXT("short"),
                 time ));
    }
  else
    {
      ACE_DEBUG((LM_INFO,
                 ACE_TEXT("Big list test(%u, %u, %u, %s) = %Q ns\n"),
                 num_list_loops,
                 num_string_loops,
                 num_seq_loops,
                 use_long_str ? ACE_TEXT("long"): ACE_TEXT("short"),
                 time ));
    }
}
Ejemplo n.º 21
0
// client main function
// uses a portable form of the "main" function along with its arguments
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{ 

  // first declare the variables
  string server_host;             // name of the server
  unsigned short port_num;        // port number is unsigned short
  unsigned short proto_type = 0;  // 0 is our dummy implementation
  size_t  chunk_size = 256;       // chunk size (default = 256)

  FileTransferClient  ftpClient;  // instantiate an object for file
                                  // transfer
  string fname;                   // name of file to transfer

  // we require the user to pass 4 arguments to the executable in that order
  // (1) the server host name 
  // (2) server port number 
  // (3) protocol to use for reliable transfer (choices are 1, 2 or 3)
  // (4) chunk size to use (optional)
  if (argc < 4) {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Usage: client <server hostname> <server port num> ")
                ACE_TEXT ("<proto type: 1 = RDT, ")
                ACE_TEXT ("2 = Go Back N, 3 = Selective Repeat> ")
                ACE_TEXT ("[<chunk size, default = 256>]\n")));
    return -1;
  }

  // let us grab the arguments
  server_host = argv [1];

  // note we have to convert to a number 
  port_num = (unsigned short) atoi (argv[2]);  

  // note we have to convert to a number 
  proto_type = (unsigned short) atoi (argv[3]);  

  // check if the user supplied a chunk size (the 4th argument)
  if (argc == 5) {  
    chunk_size = (unsigned short) atoi (argv[4]);  
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("[%P] Client - ")
              ACE_TEXT ("Server = %s, port = %d, proto = %d, ")
              ACE_TEXT ("Chunk size = %d\n"),
              server_host.c_str (), port_num, proto_type, chunk_size));

  // ask the user to enter a file name
  cout << "Please enter name of the file to transfer: ";
  cin >> fname;

  /*********************** TO-DO *************************************/
  // I will suggest that you upgrade the FileTransferClient class so
  // that it can keep a record of time taken against the chunk size and
  // the protocol type used.
  //
  // Moreover the following can be inserted into a loop where the server
  // host & port num stays same but you can vary both the proto type as
  // well as chunk size and find out the time it takes to send the same
  // file. Choose a file that is sufficiently large to show us some
  // variations. 
  /*******************************************************************/

  // now initialize the File Transfer object
  if (ftpClient.open (server_host,
                      port_num,
                      proto_type,
                      chunk_size) == -1) {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("[%P] client main - ")
                ACE_TEXT ("failed to open the object (%m)\n")));
    return -1;
  }

  // now let us time the transfer
  ACE_High_Res_Timer  timer;

  // start timing
  timer.start ();
  
  size_t bytesTransferred;  // keeps track of how many bytes were
                            // transferred 

  if ((bytesTransferred = ftpClient.SendFile (fname)) == -1) {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("[%P] client main - ")
                ACE_TEXT ("failed to send file (%m)\n")));
    return -1;
  }
  
  // time the transfer and retrieve elapsed time.
  timer.stop ();
  ACE_Time_Value tv;
  timer.elapsed_time (tv);

  // since we are done, we close the ftp object so it can clean up its
  // underlying protocol object. 
  if (ftpClient.close () == -1) {
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("[%P] client main - ")
                ACE_TEXT ("failed to close the object (%m)\n")));
    return -1;
  }
  
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("[%P] Client main - ")
              ACE_TEXT ("Total time for file transfer of %d bytes ")
              ACE_TEXT ("is %d milli seconds\n"),
              bytesTransferred, tv.msec ()));


  // everything went smoothly
  return 0;

}
Ejemplo n.º 22
0
int
ACE_TMAIN (int argc_in,
           ACE_TCHAR* argv_in[])
{
  RPG_TRACE (ACE_TEXT ("::main"));

  // step1: initialize libraries
  // *PORTABILITY*: on Windows, init ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
  if (ACE::init () == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE::init(): \"%m\", aborting\n")));
    return EXIT_FAILURE;
  } // end IF
#endif

  // step2: initialize configuration
  
  // step2a: set defaults
  RPG_Dice_ValueRange value_range;
  value_range.begin = 0;
  value_range.end = 0;
  bool print_all_results      = false;
  bool trace_information      = false;
  bool print_version_and_exit = false;

  // step2b: parse/process/validate configuration
  if (!process_arguments (argc_in,
                          argv_in,
                          print_all_results,
                          value_range,
                          trace_information,
                          print_version_and_exit))
  {
    // make 'em learn...
    print_usage (ACE::basename (argv_in[0]));

    // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", aborting\n")));
      return EXIT_FAILURE;
    } // end IF
#endif

    return EXIT_FAILURE;
  } // end IF

//   // step2c: validate arguments
//   if (valueRange.begin == valueRange.end == 0)
//   {
//     ACE_DEBUG((LM_DEBUG,
//                ACE_TEXT("invalid range: \"%s\", aborting\n"),
//                RPG_Chance_Dice_Common_Tools::rangeToString(valueRange).c_str()));
//
//     // make 'em learn...
//     print_usage();
//
//     return EXIT_FAILURE;
//   } // end IF

  // step3: initialize logging and/or tracing
  std::string log_file;
  if (!Common_Tools::initializeLogging (ACE::basename (argv_in[0]), // program name
                                        log_file,                   // logfile
                                        false,                      // log to syslog ?
                                        false,                      // trace messages ?
                                        trace_information,          // debug messages ?
                                        NULL))                      // logger
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to Common_Tools::initializeLogging(), aborting\n")));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_FAILURE;
  } // end IF

  // step4: handle specific program modes
  if (print_version_and_exit)
  {
    do_printVersion (ACE::basename (argv_in[0]));

    // *PORTABILITY*: on Windows, need to fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
    if (ACE::fini () == -1)
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE::fini(): \"%m\", continuing\n")));
#endif

    return EXIT_SUCCESS;
  } // end IF

  ACE_High_Res_Timer timer;
  timer.start ();

  // step5: do work
  RPG_Dice_Rolls_t combinations;
  do_work (value_range,
           combinations);

  timer.stop ();

  // step6: print results
  // header line
  std::cout << ACE_TEXT ("results ")
            << RPG_Dice_Common_Tools::rangeToString (value_range)
            << ACE_TEXT (": ")
            << std::endl;
  std::cout << std::setw (80)
            << std::setfill (ACE_TEXT_ALWAYS_CHAR ('-'))
            << ACE_TEXT ("")
            << std::setfill (ACE_TEXT_ALWAYS_CHAR (' '))
            << std::endl;

  bool perfect_match = true;
  int index = 1;
  RPG_Dice_ValueRange range;
  for (RPG_Dice_RollsIterator_t iterator = combinations.begin ();
       iterator != combinations.end ();
       iterator++, index++)
  {
    perfect_match = true;
    RPG_Dice::rollToRange (*iterator, range);
    if ((range.begin != value_range.begin) || (range.end != value_range.end))
    {
      // not a perfect match...
      perfect_match = false;
      if (!print_all_results)
        continue;
    } // end IF

    std::cout << ACE_TEXT ("[")
              << index
              << (perfect_match ? ACE_TEXT ("*]") : ACE_TEXT ("]"))
              << RPG_Dice_Common_Tools::rollToString (*iterator)
              << ACE_TEXT (" : ")
              << RPG_Dice_Common_Tools::rangeToString (range)
              << std::endl;
  } // end FOR

//   std::string working_time_string;
//   ACE_Time_Value working_time;
//   timer.elapsed_time(working_time);
//   RPS_FLB_Common_Tools::Period2String(working_time,
//                                       working_time_string);
  //
//   ACE_DEBUG((LM_DEBUG,
//              ACE_TEXT("total working time (h:m:s.us): \"%s\"...\n"),
//              working_time_string.c_str()));

  // step7: finalize libraries
  // *PORTABILITY*: on Windows, fini ACE...
#if defined (ACE_WIN32) || defined (ACE_WIN64)
  if (ACE::fini () == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE::fini(): \"%m\", aborting\n")));
    return EXIT_FAILURE;
  } // end IF
#endif

  return EXIT_SUCCESS;
} // end main