コード例 #1
1
int main(){
    Poco::RWLock lock;
    Task task1(1, &lock);
    Task task2(2, &lock);
    Poco::ThreadPool pool;
    pool.start(task1);
    pool.start(task2);
    pool.joinAll();
    return 0;
}
コード例 #2
0
ファイル: main.c プロジェクト: elsuizo/sAPI
/* FUNCION que contiene el planificador y despachador de tareas. */
static void scheduleAndDispatchTasks(void){

   /* Tarea planificada cada TASK1_PERIODICITY ms */
   if( task1Counter++ == TASK1_PERIODICITY ){
      /* Despacho de la tarea (la ejecuta) */
      task1();

      /* Resetea el contador de la tarea */
      task1Counter = 0;
   }

   /* Tarea planificada cada TASK2_PERIODICITY ms */
   if( task2Counter++ == TASK2_PERIODICITY ){
      /* Despacho de la tarea (la ejecuta) */
      task2();

      /* Resetea el contador de la tarea */
      task2Counter = 0;
   }

   /* Tarea planificada cada TASK3_PERIODICITY ms */
   if( task3Counter++ == TASK3_PERIODICITY ){
      /* Despacho de la tarea (la ejecuta) */
      task3();

      /* Resetea el contador de la tarea */
      task3Counter = 0;
   }

}
コード例 #3
0
ファイル: main.cpp プロジェクト: garmonbozia/home
int main ( )
{
    task1( );
    task2( );
    task3( );
    return 0;
}
コード例 #4
0
ファイル: ex_flag3.c プロジェクト: AriZuu/picoos
/* This function is executed by the first task.
 */
void task1(void *arg)
{
	VAR_t f;
	
	/* avoid compiler warning */
	(void) arg;

	for(;;) {
	
		f = posFlagGet(flagset, POSFLAG_MODE_GETSINGLE);
		
		nosPrintf("\nfirsttask: going to signal flag %i\n", f);
		
		if(f==1){
			incrementCounter(1);
			posFlagSet(flagset, 2);
			nosPrintf("flag value = %i\n",f);
			task2(arg);
		} 
		
		
		/* do something here and waste some time */
		posTaskSleep(MS(500));
	}
	
	posSemaSignal(semaphore);
	
}
コード例 #5
0
ファイル: main.cpp プロジェクト: OsipovStas/ImageAnalysis
int main(int argc, char** argv) {

    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " path/to/lena" << std::endl;
        exit(1);
    }

    cv::Mat image, orig, lena, noize, diag, tool;
    image = cv::imread(argv[1], 1);
    diag = cv::imread(DIAG, CV_LOAD_IMAGE_GRAYSCALE);
    orig = cv::imread(ORIG, CV_LOAD_IMAGE_GRAYSCALE);
    lena = cv::imread(LENA, 1);
    noize = cv::imread(NOIZE, 1);
    tool = cv::imread(TOOL, CV_LOAD_IMAGE_GRAYSCALE);

    std::cout << "Task 1 Status: " << (task1(image) ? "OK" : "Error") << std::endl;
    std::cout << "Task 2 Status: " << (task2(image) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3 Status: " << (task3(image) ? "OK" : "Error") << std::endl;
    std::cout << "Task 4 Status: " << (task4(image) ? "OK" : "Error") << std::endl;
    std::cout << "Task 5 Status: " << (task5((PATH + "noize/").c_str()) ? "OK" : "Error") << std::endl;
    std::cout << "Task 6 Status: " << (task6(image) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3.1 Status: " << (task3_1(orig) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3.2 Status: " << (task3_2(orig) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3.3 Status: " << (task3_3(tool) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3.5 Status: " << (task3_5(diag, orig) ? "OK" : "Error") << std::endl;
    std::cout << "Task 3.6 Status: " << (task3_6(lena, noize) ? "OK" : "Error") << std::endl;

    //    cv::namedWindow("Lesson 2", CV_WINDOW_NORMAL);
    //    cv::imshow("Lesson 2", image);
    //    cv::waitKey(0);
    return 0;

}
コード例 #6
0
ファイル: seos.c プロジェクト: elsuizo/sAPI
/* FUNCION que contiene el despachador de tareas. */
void seosDispatchTask(void){

   /* Tarea planificada cada TASK1_PERIODICITY ms */
   if( task1RunFlag ){
      /* Si el flag esta en 1 despacha de la tarea 
         (la ejecuta) */
      task1();

      /* Resetea el flag de ejecucion de la tarea */
      task1RunFlag = 0;
   }

   /* Tarea planificada cada TASK2_PERIODICITY ms */
   if( task2RunFlag ){
      /* Si el flag esta en 1 despacha de la tarea 
         (la ejecuta) */
      task2();

      /* Resetea el flag de ejecucion de la tarea */
      task2RunFlag = 0;
   }

   /* Tarea planificada cada TASK3_PERIODICITY ms */
   if( task3RunFlag ){
      /* Si el flag esta en 1 despacha de la tarea 
         (la ejecuta) */
      task3();

      /* Resetea el flag de ejecucion de la tarea */
      task3RunFlag = 0;
   }

}
コード例 #7
0
void
PriorityTapeTest::testPriority()
{
    boost::posix_time::ptime begin;
    boost::posix_time::ptime current;
    int duration;


    CPPUNIT_ASSERT( true == priority_->Enable(true) );

    PriorityTapeTask task0(priority_.get(),100,0,10);
    PriorityTapeTask task1(priority_.get(),100,1,10);
    PriorityTapeTask task2(priority_.get(),100,2,10);
    PriorityTapeTask task3(priority_.get(),100,3,10);
    PriorityTapeTask task4(priority_.get(),100,4,10);
    PriorityTapeTask task5(priority_.get(),100,5,10);

    task0.Start();
    boost::this_thread::sleep(
        boost::posix_time::milliseconds(5) );
    task1.Start();
    task2.Start();
    task3.Start();
    task4.Start();
    task5.Start();
    CPPUNIT_ASSERT( false == task0.Finished() );
    CPPUNIT_ASSERT( false == task1.Finished() );
    CPPUNIT_ASSERT( false == task2.Finished() );
    CPPUNIT_ASSERT( false == task3.Finished() );
    CPPUNIT_ASSERT( false == task4.Finished() );
    CPPUNIT_ASSERT( false == task5.Finished() );
    boost::this_thread::sleep(
        boost::posix_time::milliseconds(100) );
    CPPUNIT_ASSERT( true == task0.Finished() );
    CPPUNIT_ASSERT( true == task5.Finished() );
    CPPUNIT_ASSERT( true == task4.Finished() );
    CPPUNIT_ASSERT( true == task3.Finished() );
    CPPUNIT_ASSERT( true == task2.Finished() );
    CPPUNIT_ASSERT( true == task1.Finished() );

    duration = (task0.End() - task0.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    duration = (task1.End() - task1.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    duration = (task2.End() - task2.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    duration = (task3.End() - task3.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    duration = (task4.End() - task4.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    duration = (task5.End() - task5.Begin()).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 );
    CPPUNIT_ASSERT( task0.End() <= task5.Begin() );
    CPPUNIT_ASSERT( task5.End() <= task4.Begin() );
    CPPUNIT_ASSERT( task4.End() <= task3.Begin() );
    CPPUNIT_ASSERT( task3.End() <= task2.Begin() );
    CPPUNIT_ASSERT( task2.End() <= task1.Begin() );
}
コード例 #8
0
int main(){
    boost::mutex mutex;
    Task task1(1, &mutex);
    Task task2(2, &mutex);
	
	boost::thread th1(&Task::run, &task1); 
	boost::thread th2(&Task::run, &task2); 
	th1.join();
	th2.join();	
    return 0;
}
コード例 #9
0
ファイル: task.c プロジェクト: jian-tian/myproc
void init_task()
{
    //task0();
    //task1();
    task2();
    task3();
    //task4();
    //task5();
    printfk("init_task ok.\n\r");
    return;
}
コード例 #10
0
ファイル: condition.cpp プロジェクト: sauver/sauver_sys
int main()
{
  int i, sleepTime;
  // The condition the threads will be using
  ArCondition cond;
  // The threads
  Task task1(1, &cond);
  Task task2(2, &cond);
  Task task3(3, &cond);
  Task task4(4, &cond);

  // Initialize Aria, which in turn initializes the thread layer
  Aria::init();

  // Initialize the rand() function
  srand((unsigned)time(NULL));

  // Lets start all correct threads.
  task1.create();
  task2.create();
  task3.create();
  task4.create();

  // Lets wake up the threads at different random times
  for (i=0; i<10; ++i)
  {
    sleepTime=rand()%400+100;
    printf("Main: Sleeping %dms\n", sleepTime);
    ArUtil::sleep(sleepTime);
    printf("Main: Waking up a thread\n");
    cond.signal();
  }

  printf("Exiting\n");

  // Stop all the threads, which sets their running variable to false
  ArThread::stopAll();

  // Now that all the threads are marked as not running, wake them up
  // so that we can exit the program gracefully.
  cond.broadcast();

  // Wait for all the threads to exit
  ArThread::joinAll();

  // Uninit Aria
  Aria::uninit();

  return(0);
}
コード例 #11
0
int main() {

	std::thread task1(foo);
	std::thread task2(bar, 5, 2);

	std::cout << "main, foo and bar now execute concurrently...\n";

	// synchronize threads:
	task1.join();                // pauses until first finishes
	task2.join();               // pauses until second finishes

	std::cout << "foo and bar completed.\nNow I'll finish\n";

	return 0;
}
コード例 #12
0
int main() {
    // task 1
    std::packaged_task<int(int)> task1(mult2);
    std::future<int> fut1 = task1.get_future();
    task1(3);
    std::cout << fut1.get() << std::endl;

    // task 2
    std::packaged_task<long(int)> task2(mult2);
    std::future<long> fut2 = task2.get_future();
    task2(4);
    std::cout << fut2.get() << std::endl;

    // task 3
    std::packaged_task<int(int)> task3(mult2);
    task3(5);
    std::future<int> fut3 = task3.get_future();
    std::cout << fut3.get() << std::endl;

    // task 4
    std::packaged_task<void()> task4([]{std::cout << "void" << std::endl;});
    task4();
    task4.get_future().get();
}
コード例 #13
0
ファイル: main.cpp プロジェクト: wopqw/Cpp
int main(int argc, const char * argv[]) {
    // insert code here...
    int t;
    printf("Меню:\n1)Все числа от 1 до n\n2)Все числа от А до В\n3)Функция Аккермана\n4)Точная степень двойки\n5)Сумма цифр числа\n");
    printf("Выберите номер задания\n");
    scanf("%d",&t);
    while(t!=6)
    {
        switch(t)
        {
            case 1:
            {
                printf("Все числа от 1 до n\n");
                task1();
                break;
            }
            case 2:
            {
                printf("Все числа от А до В\n");
                task2();
                break;
            }
            case 3:
            {
                printf("Функция Аккермана\n");
                task3();
                break;
            }
            case 4:
            {
                printf("Точная степень двойки\n");
                task4();
                break;
            }
            case 5:
            {
                printf("Сумма цифр числа\n");
                task5();
                break;
            }
        }
        printf("\nМеню:\n1)Все числа от 1 до n\n2)Все числа от А до В\n3)Функция Аккермана\n4)Точная степень двойки\n5)Сумма цифр числа\n");
        printf("Выберите номер задания\n");
        scanf("%d",&t);
    }
    return 0;
}
コード例 #14
0
void
runTestMulti()
{
#if defined(DEBUG)
  os::diag::trace.putString(__PRETTY_FUNCTION__);
  os::diag::trace.putNewLine();
#endif

  ts.setClassName("os::core::Thread");
  ts.setFunctionNameOrPrefix("sleep()");

  Task task1("T1", hal::arch::MIN_STACK_SIZE);
  Task task2("T2", hal::arch::MIN_STACK_SIZE);
  Task task3("T3", hal::arch::MIN_STACK_SIZE);
  Task task4("T4", hal::arch::MIN_STACK_SIZE);
  Task task5("T5", hal::arch::MIN_STACK_SIZE);

  Task* taskArray[5] =
    { &task1, &task2, &task3, &task4, &task5 };

  for (auto pTask : taskArray)
    {
      ts.setPreconditions(pTask->getName());
      ts.assertCondition(pTask->getCount() == 0);
    }

  for (auto pTask : taskArray)
    {
      ts.assertCondition(pTask->getThread().start());
    }

  for (auto pTask : taskArray)
    {
      pTask->getThread().join();
    }

  for (auto pTask : taskArray)
    {
      ts.setPreconditions(pTask->getName());
      ts.assertCondition(
          ((pTask->getDeltaTicks() - pTask->getCount())
              <= pTask->getSleepCalls()));
    }

}
コード例 #15
0
TEST(MessageLoopThreadUnitTest, PostTwoTask)
{
    bool bValue = false;
    ToggleValueTask task(&bValue);
    TaskClosure taskClosure1 = CreateTaskClosure(&ToggleValueTask::Run, &task);

    SleepTask task2(1000);
    TaskClosure taskClosure2 = CreateTaskClosure(&SleepTask::Run, &task2);

    MessageLoopThread thread(_T("togglevalue"));
    ASSERT_TRUE(thread.Start());

    thread.GetMessageLoop()->PostTask(taskClosure1);
    thread.GetMessageLoop()->PostTask(taskClosure2);

    // wait for the task to finish
    Sleep(5 * 1000);

    ASSERT_TRUE(bValue);
}
コード例 #16
0
const TaskList& BackendIntegrationTests::referenceTasks()
{
    static TaskList Tasks;
    if ( Tasks.isEmpty() ) {
        Task task1( 1000, "Task 1" );
        Task task1_1( 1001, "Task 1-1", task1.id() );
        Task task1_2( 1002, "Task 1-2", task1.id() );
        Task task1_3( 1003, "Task 1-3", task1.id() );
        Task task2( 2000, "Task 2" );
        Task task2_1( 2100, "Task 2-1", task2.id() );
        Task task2_1_1( 2110, "Task 2-1-1", task2_1.id() );
        Task task2_1_2( 2120, "Task 2-1-2", task2_1.id() );
        Task task2_2( 2200, "Task 2-2", task2.id() );
        Task task2_2_1( 2210, "Task 2-2-1", task2_2.id() );
        Task task2_2_2( 2220, "Task 2-2-2", task2_2.id() );
        Tasks << task1 << task1_1 << task1_2 << task1_3
              << task2 << task2_1 << task2_1_1 << task2_1_2
              << task2_2 << task2_2_1 << task2_2_2;
    }
    return Tasks;
}
コード例 #17
0
ファイル: CharmDataModelTests.cpp プロジェクト: hefee/Charm
void CharmDataModelTests::initTestCase ()
{
    // set up a model that the other tests can clone to use:
    m_referenceModel = new CharmDataModel;
    Task task1( 1000, "Task 1" );
    Task task1_1( 1001, "Task 1-1", task1.id() );
    Task task1_2( 1002, "Task 1-2", task1.id() );
    Task task1_3( 1003, "Task 1-3", task1.id() );
    Task task2( 2000, "Task 2" );
    Task task2_1( 2100, "Task 2-1", task2.id() );
    Task task2_1_1( 2110, "Task 2-1-1", task2_1.id() );
    Task task2_1_2( 2120, "Task 2-1-2", task2_1.id() );
    Task task2_2( 2200, "Task 2-2", task2.id() );
    Task task2_2_1( 2210, "Task 2-2-1", task2_2.id() );
    Task task2_2_2( 2220, "Task 2-2-2", task2_2.id() );
    TaskList tasks;
    tasks << task1 << task1_1 << task1_2 << task1_3
          << task2 << task2_1 << task2_1_1 << task2_1_2
          << task2_2 << task2_2_1 << task2_2_2;
    // test setAllTasks, only slightly, more detailed tests follow
    m_referenceModel->setAllTasks( tasks );
    QVERIFY( m_referenceModel->taskTreeItem( task2_2.id() ).childCount() == 2 );
    QVERIFY( m_referenceModel->taskTreeItem( task2.id() ).childCount() == 2 );
}
コード例 #18
0
ファイル: client.cpp プロジェクト: CCJY/ATCD
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int priority =
    (ACE_Sched_Params::priority_min (ACE_SCHED_FIFO)
     + ACE_Sched_Params::priority_max (ACE_SCHED_FIFO)) / 2;
  // Enable FIFO scheduling, e.g., RT scheduling class on Solaris.

  if (ACE_OS::sched_params (ACE_Sched_Params (ACE_SCHED_FIFO,
                                              priority,
                                              ACE_SCOPE_PROCESS)) != 0)
    {
      if (ACE_OS::last_error () == EPERM)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "client (%P|%t): user is not superuser, "
                      "test runs in time-shared class\n"));
        }
      else
        ACE_ERROR ((LM_ERROR,
                    "client (%P|%t): sched_params failed\n"));
    }


  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) != 0)
        return 1;

      CORBA::Object_var object =
        orb->string_to_object (ior);

      Test::Roundtrip_var roundtrip =
        Test::Roundtrip::_narrow (object.in ());

      if (CORBA::is_nil (roundtrip.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Nil Test::Roundtrip reference <%s>\n",
                             ior),
                            1);
        }

          /// Begin the test

      ACE_DEBUG ((LM_DEBUG, "Starting threads\n"));

      Client_Task task0 (data_type, sz, roundtrip.in (), niterations);
      Client_Task task1 (data_type, sz, roundtrip.in (), niterations);
      Client_Task task2 (data_type, sz, roundtrip.in (), niterations);
      Client_Task task3 (data_type, sz, roundtrip.in (), niterations);

      ACE_hrtime_t test_start = ACE_OS::gethrtime ();
      task0.activate (THR_NEW_LWP | THR_JOINABLE);
      task1.activate (THR_NEW_LWP | THR_JOINABLE);
      task2.activate (THR_NEW_LWP | THR_JOINABLE);
      task3.activate (THR_NEW_LWP | THR_JOINABLE);

      task0.thr_mgr()->wait ();
      ACE_hrtime_t test_end = ACE_OS::gethrtime ();

      ACE_DEBUG ((LM_DEBUG, "Threads finished\n"));

      ACE_DEBUG ((LM_DEBUG, "High resolution timer calibration...."));
      ACE_High_Res_Timer::global_scale_factor_type gsf =
        ACE_High_Res_Timer::global_scale_factor ();
      ACE_DEBUG ((LM_DEBUG, "done\n"));

      ACE_Basic_Stats totals;
      task0.accumulate_and_dump (totals, ACE_TEXT("Task[0]"), gsf);
      task1.accumulate_and_dump (totals, ACE_TEXT("Task[1]"), gsf);
      task2.accumulate_and_dump (totals, ACE_TEXT("Task[2]"), gsf);
      task3.accumulate_and_dump (totals, ACE_TEXT("Task[3]"), gsf);

      totals.dump_results (ACE_TEXT("Total"), gsf);

      ACE_Throughput_Stats::dump_throughput (ACE_TEXT("Total"), gsf,
                                             test_end - test_start,
                                             totals.samples_count ());

      if (do_shutdown)
        {
          roundtrip->shutdown ();
        }
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught:");
      return 1;
    }

  return 0;
}
コード例 #19
0
int
run_main (int argc, ACE_TCHAR *argv[])
{
#if defined (ACE_HAS_WIN32_PRIORITY_CLASS)
  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("dp:"));
#else
  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("d"));
#endif
  int opt;
  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
          case 'd':
            debug_test = 1u;
            break;
#if defined (ACE_HAS_WIN32_PRIORITY_CLASS)
          case 'p':
            process_id = ACE_OS::atoi (get_opt.opt_arg ());
            break;
#endif
        }
    }

  if (get_opt.opt_ind () == argc - 1)
    {
      // child process: sleep & exit
      ACE_TCHAR lognm[MAXPATHLEN];
      int const mypid (ACE_OS::getpid ());
      ACE_OS::snprintf (lognm, MAXPATHLEN,
                        ACE_TEXT ("Process_Manager_Test-child-%d"), mypid);

      ACE_START_TEST (lognm);
      int const secs = ACE_OS::atoi (argv[get_opt.opt_ind ()]);
      ACE_OS::sleep (secs ? secs : 1);

      ACE_TCHAR prio[64];
#if defined (ACE_WIN32_HAS_PRIORITY_CLASS)
      DWORD priority = ::GetPriorityClass (::GetCurrentProcess());

      check_process_priority(priority);

      if (priority == ABOVE_NORMAL_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'above normal'"));
      else if (priority == BELOW_NORMAL_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'below normal'"));
      else if (priority == HIGH_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'high'"));
      else if (priority == IDLE_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'idle'"));
      else if (priority == NORMAL_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'normal'"));
      else if (priority == REALTIME_PRIORITY_CLASS)
        ACE_OS::snprintf (prio, 64, ACE_TEXT ("and priority 'realtime'"));
#else
      prio[0] = ACE_TEXT ('\0');
#endif
      if (debug_test)
        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("%T: pid %P about to exit with code %d %s\n"),
                    secs,
                    prio));
      ACE_END_LOG;

      return secs;
    }

  if (get_opt.opt_ind () != argc)      // incorrect usage
    usage (argv[0]);

  ACE_START_TEST (ACE_TEXT ("Process_Manager_Test"));

  int test_status = 0;

#ifdef ACE_HAS_PROCESS_SPAWN

  int result = 0;
  if ((result = command_line_test ()) != 0)
    test_status = result;

  // Try the explicit <ACE_Process_Manager::wait> functions

  ACE_Process_Manager mgr;

  mgr.register_handler (new Exit_Handler ("default"));

  ACE_exitcode exitcode;

  // --------------------------------------------------
  // wait for a specific PID
  pid_t child1 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              1,
                              1);
  result = mgr.wait (child1,
                     &exitcode);

  if (result != child1)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) Error: expected to reap child1 (%d); got %d\n"),
                  child1,
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) reaped child1, pid %d: %d\n"),
                child1,
                exitcode));

  // --------------------------------------------------
  // wait for a specific PID; another should finish first
  pid_t child2 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              1,
                              2);
  pid_t child3 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              4,
                              3);
  result = mgr.wait (child3,
                     &exitcode);

  if (result != child3)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) Error: expected to reap child3 (%d); got %d\n"),
                  child3,
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) reaped child 3, pid %d: %d\n"),
                child3,
                exitcode));

  // Now wait for any...should get the one that finished earlier.

  result = mgr.wait (0, &exitcode);

  if (result != child2)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) Error: expected to reap child2 (%d); got %d\n"),
                  child2,
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) reaped child 2, pid %d: %d\n"),
                result,
                exitcode));

  // --------------------------------------------------
  // Try the timed wait functions

  // This one shouldn't timeout:
  pid_t child4 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              1,
                              4);
#if defined (ACE_HAS_CPP11)
  result = mgr.wait (0, std::chrono::seconds (4), &exitcode);
#else
  result = mgr.wait (0, ACE_Time_Value (4), &exitcode);
#endif

  if (result != child4)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) Error: expected to reap child4 (%d); got %d\n"),
                  child4,
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) reaped child 4 pid %d: %d\n"),
                result,
                exitcode));

  // This one should timeout:
  pid_t child5 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              4,
                              5);
  result = mgr.wait (0, ACE_Time_Value (1), &exitcode);
  if (result != 0)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) Error: expected wait to time out; got %d\n"),
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) Correctly timed out wait at child 5\n")));

  // Now wait indefinitely to clean up...
  result = mgr.wait (0, &exitcode);

  if (result != child5)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Error: expected to reap child5 pid %d; got %d\n"),
                  child5,
                  result));
      if (result == ACE_INVALID_PID)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("error")));
      test_status = 1;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%P) reaped child 5, pid %d: %d\n"),
                result,
                exitcode));

  // Terminate a child process and make sure we can wait for it.
  pid_t child6 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              5,
                              6);
  ACE_exitcode status6;
  if (-1 == mgr.terminate (child6))
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P) %p\n"), ACE_TEXT ("terminate child6")));
      test_status = 1;
      mgr.wait (child6, &status6);  // Wait for child to exit just to clean up
    }
  else
    {
      if (-1 == mgr.wait (child6, &status6))
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P) wait on child6 reported ACE_INVALID_PID\n")));
          test_status = 1;
        }
      else
        {
          // Get the results of the termination.
#if !defined(ACE_WIN32)
          if (WIFSIGNALED (status6) != 0)
            ACE_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("(%P) child6 died on signal %d - correct\n"),
                        WTERMSIG (status6)));
          else
            ACE_ERROR ((LM_ERROR,
                        ACE_TEXT ("(%P) child6 should have died on signal, ")
                        ACE_TEXT ("but didn't; exit status %d\n"),
                        WEXITSTATUS (status6)));
#else
          ACE_DEBUG
            ((LM_DEBUG,
              ACE_TEXT ("(%P) The process terminated with exit code %d\n"),
              status6));
#endif /*ACE_WIN32*/
        }
    }

#ifdef ACE_HAS_THREADS
  Process_Task task1 (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"), mgr, 3);
  Process_Task task2 (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"), mgr, 2);
  Process_Task task3 (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"), mgr, 1);
  task1.open (0);
  task2.open (0);
  task3.open (0);

  while (running_tasks!=0)
    {
      ACE_OS::sleep (1);
      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P) still running tasks\n")));
    }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P) result: '%C'\n"),
              order.c_str ()));

  if (order != "321123")
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P) wrong order of spawns ('%C', should be '321123')\n"),
                  order.c_str ()));
      test_status = 1;
    }
#endif /* ACE_HAS_THREADS */

#if !defined (ACE_OPENVMS) && \
  (defined ACE_WIN32 || !defined ACE_LACKS_UNIX_SIGNALS)
  // --------------------------------------------------
  // Finally, try the reactor stuff...
  mgr.open (ACE_Process_Manager::DEFAULT_SIZE,
            ACE_Reactor::instance ());

  pid_t child7 = spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                              mgr,
                              5,
                              7);
  /* pid_t child8 = */ spawn_child (argc > 0 ? argv[0] : ACE_TEXT ("Process_Manager_Test"),
                                    mgr,
                                    6,
                                    0);

  mgr.register_handler (new Exit_Handler ("specific"),
                        child7);

  ACE_Time_Value how_long (10);

  ACE_Reactor::instance ()->run_reactor_event_loop (how_long);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P) Reactor loop done!\n") ));

  size_t const nr_procs = mgr.managed ();
  if (nr_procs != 0)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("(%P) %d processes left in manager\n"),
                nr_procs));
#endif /* !defined (ACE_OPENVMS) */
#endif // ACE_HAS_PROCESS_SPAWN
  ACE_END_TEST;
  return test_status;
}
コード例 #20
0
int main()
{

//File variables
FILE *ifp;
char *mode="r";
char *fileName="tic-tac-toe.data";

//Data Structure that will receive the file info
int data [958][10];


//////////////opening and reading file////////////////////

ifp= fopen(fileName, mode);

//Verifing if the file was open correctly
if(ifp!=NULL){
	printf("File successfully opened!\n");

	//Reading each character of the opened file
	char ch;
	int i=0;
	int j=0;
	int insertedValue;

	while( ( ch = fgetc(ifp) ) != EOF ){

		if(ch=='x' || ch=='o' || ch=='b' || ch=='p' || ch=='n'){ //ignore any other character

			//load the file into the selected data structure
			if(ch=='x'){
				insertedValue= 1;

			}else if(ch=='o'){
				insertedValue= 0;

			}else if(ch=='b'){
				insertedValue= -1;

			}else if(ch=='p'){
				insertedValue= 1;
				fgetc(ifp);

			}else{
				insertedValue= 2;

			}

			data[i][j]=insertedValue;
			j++;

			//adjusting i and j
			if(j==10){
				j=0;
				i++;
			}

		}

	}

	
	fclose(ifp);

}else{
	printf("The file was not open!\n");
}


//Writing file with numerical data
	//Label used= 1 for positive cases and 2 for negative cases

FILE *ofp;
ofp= fopen("tic-tac-toe-numerical.csv", "w");

if(ofp!=NULL){
	printf("File successfully opened for Writing!\n");

	for (int i = 0; i < 958; i++)
	{	//Label

		for(int j = 0; j < 9; j++)
		{	
		fprintf(ofp, " %d,",data[i][j]);
		}
		fprintf(ofp, "%d\n", data[i][9]);
	}

}else{
	printf("The file was not open!\n");
}
fclose(ofp);
 	





//////////////////////data structure uploaded//////////////////
//Task 1
	FILE *resultsFuzzyFile;
	resultsFuzzyFile= fopen("Results/resultsTaks1.txt", "w");

	//Executes the algorith of task1 and prints its results into the file "Results/resultsTaks1.txt"
	task1(data,resultsFuzzyFile);

	fclose(resultsFuzzyFile);
	

//Task 2

//Tasks
/*Algorithm:
	-Create folder randomically (positive and negative)
		-do 10x	
			-do 62x {fill the array with positives}
			-do 33x {fill the array with negatives}
	-Do 10x
		-Create a new array of trainingData and validationData
		-Train with 9 folders and validate with 1
			-Enter function: kData, startValidationData, numberPositive, numberNegative, numberFolder
			-Inside the tasks when training ask to skip the range of the validationData
			-and when validating just use the range of the validationData
		-Update startValidationData 
*/

		//With cross validation

		//Randomize input data
// 		//Each folder will contain 95 samples (62 positive / 33 negative) that will be chosen randomly
		FILE *resultsBayesFile;
		resultsBayesFile= fopen("Results/errorBayesian.txt", "w");
		FILE *resultsKNNFile;
		resultsKNNFile= fopen("Results/errorKNN15.txt", "w");
		FILE *resultsSumFile;
		resultsSumFile= fopen("Results/errorSum.txt", "w");

		char kfoldName[1000];
		FILE *filekfold;

		char kfoldRead[1000];
		FILE *filekfoldRead;


		int nFold=10;
		int nPositive=62;
		int nNegative=33;
		int nTotal=nPositive+nNegative;
		

		int kData [nTotal*nFold][10];
		int n[950];
		for(int i=0; i<950; i++){
				n[i]=i;
		}

		//Calling tasks to execute with cross validation

		int executeKFold=10;
		float meansTask2 [100];
		float meansTask2b[100];
		float meansTask2SumRule[100];
		int cont=0;


		//Execute k-fold 10x... in the end we are going to have 100 samples

		for (int j = 0; j < executeKFold ; j++)
		{
			

		//ATTENTION: Just run this part of the experiment once in ordet to create the k-fold files
		//If you want to create a new k-fold data uncomment the code below

		// sprintf(kfoldName,"data_kfold/OTHERS/%i", j);
		// filekfold=fopen(kfoldName,"w");
			
		// //Creating randomized array as base
		// randArray(n,626);
		// randArray(&n[626], 332);

		// int P=0;
		// int N=626;
		// int i=0;

		// 	//Filling folders
		// 	for (int f = 0; f < nFold ; f++){
				
		// 		int pAux= P+nPositive;
		// 		for (; P < pAux ; P++, i++)
		// 		{	
		// 			for (int j = 0; j < 9; j++)
		// 			{
		// 				kData[i][j]=data[n[P]][j];
		// 				fprintf(filekfold, "%i ", kData[i][j]);
		// 			}
		// 			kData[i][9]=data[n[P]][9];
		// 			fprintf(filekfold, "%i\n", kData[i][9]);
		// 		}

		// 		int nAux= N+nNegative;
		// 		for (; N < nAux; N++, i++)
		// 		{
		// 			for (int j = 0; j < 9; j++)
		// 			{
		// 				kData[i][j]=data[n[N]][j];
		// 				fprintf(filekfold, "%i ", kData[i][j]);
		// 			}
		// 			kData[i][9]=data[n[N]][9];
		// 			fprintf(filekfold, "%i\n", kData[i][9]);
		// 		}
		// 	}
		// fclose(filekfold);

		//Loading k-fold data
		//If the code above is uncommented, comment this part below the LOAD 
		sprintf(kfoldRead,"data_kfold/OTHERS/%i", j);
		printf("%s\n", kfoldRead);
		filekfoldRead=fopen(kfoldRead,"r");

		for (int i = 0; i < 950; ++i)
		{
			for (int j = 0; j < 10; ++j)
			{
				fscanf(filekfoldRead,"%i",&kData[i][j]);
			}
		}
		
		fclose(filekfoldRead);
		//////////////////////////////////////////////////////


			int startValidation=0;
			int startValidation2=nPositive+nNegative;

			for (int i = 0; i < nFold; i++)
			{
				//Writing k-fold data on files
				//Writing on file for the SVM classifier
				//Label used= +1 for positive cases and -1 for negative cases

				char *path= ""; //I did not manage to use relative pahth
				//SVM input
				char trainingNameSVM[1000];
				//Path to the project folder
				sprintf(trainingNameSVM,"%sdata_kfold/SVM/%i/SVMtraining%i.csv",path,j,i);
				//printf("%s\n", trainingNameSVM);
				char testNameSVM[1000];
				sprintf(testNameSVM,"%sdata_kfold/SVM/%i/SVMtest%i.csv",path,j,i);
				char *modeW="w";

				FILE *fTraining;
				FILE *fTest;
				fTraining= fopen(trainingNameSVM, modeW);
				fTest=fopen(testNameSVM,modeW);

				if(fTraining!=NULL || fTest!=NULL){
					printf("SVM File successfully opened for Writing!\n");
					
					for (int l = 0; l < 950; l++)
					{	//Label
						if(l<startValidation || l>=(startValidation+(nPositive+nNegative))){
							
							for (int j = 0; j < 9; j++)
							{	
								fprintf(fTraining, "%d,",kData[l][j]);
							}
							fprintf(fTraining, "%d", kData[l][9]);
							fprintf(fTraining, "\n");
						}else{
							
							for (int j = 0; j < 9; j++)
							{	
								fprintf(fTest, "%d,",kData[l][j]);
							}
							fprintf(fTest, "%d", kData[l][9]);
							fprintf(fTest, "\n");
						}
					}

				}else{
					printf("The SVM file was not open!\n");
				}

				fclose(fTraining);
				fclose(fTest);

				if(i==0){
				//MLP input
				char trainingNameMLP[1000];
				sprintf(trainingNameMLP,"%sdata_kfold/MLP/MLP%i.csv",path,j);
				

				FILE *fTrainingMLP;
				
				fTrainingMLP= fopen(trainingNameMLP, modeW);
				

				if(fTrainingMLP!=NULL){
					printf("MLP File successfully opened for Writing!\n");

					for (int l = 0; l < 950; l++)
					{
							
							for (int j = 0; j < 9; j++)
							{	
								fprintf(fTrainingMLP, "%d,",kData[l][j]);
							}

							if(kData[l][9]==2){
								fprintf(fTrainingMLP, "%d,", 0);
								fprintf(fTrainingMLP, "%d", 1);
							}else{
								fprintf(fTrainingMLP, "%d,", 1);
								fprintf(fTrainingMLP, "%d", 0);
							}
							fprintf(fTrainingMLP, "\n");
						
					}

				}else{
					printf("The MLP file was not open!\n");
				}
				
				fclose(fTrainingMLP);
				}

				//Task 2: Naive Bayesian Classifier
				meansTask2[cont]=task2(kData, startValidation,nPositive,nNegative,nTotal*nFold,nFold);
				printf("Bayesian: %f\n", meansTask2[cont]);
				fprintf(resultsBayesFile, "%f\n", meansTask2[cont]);
				//Task 2b: KNN
				meansTask2b[cont]=task2b(kData, startValidation,nPositive,nNegative,nTotal*nFold,nFold);
				printf("KNN: %f\n", meansTask2b[cont]);
				fprintf(resultsKNNFile, "%f\n", meansTask2b[cont]);

				meansTask2SumRule[cont]=task2SumRule(kData, startValidation,nPositive,nNegative,nTotal*nFold,nFold);
				printf("SumRule: %f\n",meansTask2SumRule[cont]);
				fprintf(resultsSumFile, "%f\n", meansTask2SumRule[cont]);

				cont++;
				
				//Updating trainingData and validationData
				startValidation+=(nPositive+nNegative);
				if(i<8){
					startValidation2+=(nPositive+nNegative);
				}else{
					startValidation2=0;
				}
				
			}
		}

		fclose(resultsBayesFile);
		fclose(resultsKNNFile);
		fclose(resultsSumFile);
		

return 0;
}
コード例 #21
0
ファイル: Scheduler_ut.cpp プロジェクト: adnap117/libSPRITE
    void Scheduler_ut::test_schedules()
    {
        IPRINTF("\nExecuting %s\n", __func__);
        Task_db::value_t task_props;
        Scheduler &sched = Scheduler::get_instance();
#if 0

        /* Halt the scheduler.
         */
        sched.stop();

        /* Store the task properties.
         */
        task_props.prio = 98;
        task_props.period = sched_period;

        CPPUNIT_ASSERT_EQUAL(true, sched.set_properties(task_props));
#endif

        CPPUNIT_ASSERT_EQUAL((unsigned)0, sched.get_schedule());

        for(schedule_t i = 0; i < 32; ++i)
        {
            sched.set_schedule(i);
            CPPUNIT_ASSERT_EQUAL(i, sched.get_schedule());
        }

        /* Create the tasks and make sure they're valid.
         */
        task_props.period = units::Nanoseconds(20 * units::MSEC);
        task_props.prio = higher_priority;
        task_props.schedule_presence = 0x000A; // 1010
        Test_task task1("task_1", 1);
        CPPUNIT_ASSERT_EQUAL(true, task1.set_properties(task_props));
        CPPUNIT_ASSERT_EQUAL(true, task1.is_valid());

        task_props.prio = lower_priority;
        task_props.schedule_presence = 0x000D; // 1101
        Test_task task2("task_2", 2);
        CPPUNIT_ASSERT_EQUAL(true, task2.set_properties(task_props));
        CPPUNIT_ASSERT_EQUAL(true, task2.is_valid());

        sched.set_schedule(31);

        /* Off to the races.
         */
        CPPUNIT_ASSERT_EQUAL(true, task1.start());
        CPPUNIT_ASSERT_EQUAL(true, task2.start());
        // CPPUNIT_ASSERT_EQUAL(true, sched.start());

        IPRINTF("\nTesting multiple schedules.\n"
                "This test will take at least 4 seconds to complete.\n");
        for(int i = 0; i < 4; ++i)
        {
            sched.set_schedule(i);

            /* Not the most reliable timing method.
             */
            sleep(units::Nanoseconds(1 * units::SEC));

            sched.set_schedule(31);

            /* Check the counters to see if the counts match. Allow some
             * variance to account for the imprecision of halting the task
             * based on a timer.
             */
            if(task1.is_present_in_schedule(i))
            {
                CPPUNIT_ASSERT((counter[1] >= 48) && (counter[1] <= 60));
            }
            else
            {
                CPPUNIT_ASSERT_EQUAL(0, counter[1]);
            }

            if(task2.is_present_in_schedule(i))
            {
                CPPUNIT_ASSERT((counter[2] >= 48) && (counter[2] <= 60));
            }
            else
            {
                CPPUNIT_ASSERT_EQUAL(0, counter[2]);
            }

            counter[1] = 0;
            counter[2] = 0;
        }

        DPRINTF("Halting all test tasks\n");
        DPRINTF("Stopping task 1\n");
        task1.stop();
        DPRINTF("Stopping task 2\n");
        task2.stop();

        sched.set_schedule(0);
        CPPUNIT_ASSERT_EQUAL((unsigned)0, sched.get_schedule());
    }
コード例 #22
0
ファイル: Scheduler_ut.cpp プロジェクト: adnap117/libSPRITE
    void Scheduler_ut::test_tasks()
    {
        IPRINTF("\nExecuting %s\n", __func__);
        /* Create the tasks.
         */
        Task_properties tprops;
        tprops.period = units::Nanoseconds(20 * units::MSEC);
        tprops.prio = higher_priority;
        Test_task task1("task_2_1", 1);
        CPPUNIT_ASSERT_EQUAL(true, task1.set_properties(tprops));
        CPPUNIT_ASSERT_EQUAL(true, task1.is_valid());

        tprops.prio = lower_priority;
        Test_task task2("task_2_2", 2);
        CPPUNIT_ASSERT_EQUAL(true, task2.set_properties(tprops));
        CPPUNIT_ASSERT_EQUAL(true, task2.is_valid());

        tprops.period = units::Nanoseconds(10 * units::MSEC);
        tprops.prio = highest_priority;
        Test_task task3("task_1_3", 3);
        CPPUNIT_ASSERT_EQUAL(true, task3.set_properties(tprops));
        CPPUNIT_ASSERT_EQUAL(true, task3.is_valid());

        tprops.period = units::Nanoseconds(40 * units::MSEC);
        tprops.prio = lowest_priority;
        Test_task task4("task_4_4", 4);
        CPPUNIT_ASSERT_EQUAL(true, task4.set_properties(tprops));
        CPPUNIT_ASSERT_EQUAL(true, task4.is_valid());

        /* Set up this task with invalid period (faster than the scheduler).
         */
        tprops.period = units::Nanoseconds(sched_period / 2);
        tprops.prio = lowest_priority;
        Test_task task5("task_invalid_period", 5);
        CPPUNIT_ASSERT_EQUAL(true, task5.set_properties(tprops));
        CPPUNIT_ASSERT_EQUAL(true, task5.is_valid());

        /* Runtimes should be zero before the task starts.
         */
        units::Nanoseconds last_runtime = task1.get_last_runtime();
        CPPUNIT_ASSERT_EQUAL(units::Nanoseconds(0), last_runtime);
        CPPUNIT_ASSERT_EQUAL(units::Nanoseconds(0), task1.get_max_runtime());

        /* Off to the races.
         */
        task_terminated = false;
        CPPUNIT_ASSERT_EQUAL(true, task1.start());
        CPPUNIT_ASSERT_EQUAL(true, task2.start());
        CPPUNIT_ASSERT_EQUAL(true, task3.start());
        CPPUNIT_ASSERT_EQUAL(true, task4.start());

        IPRINTF("\nTesting invalid period, an error is expected\n");
        CPPUNIT_ASSERT_EQUAL(false, task5.start());

        /* Not the most reliable timing method.
         */
        sleep(units::Nanoseconds(1 * units::SEC));

        /* Stop the tasks so the counters stop incrementing. This makes
         * cleanup faster too.
         */
        DPRINTF("Halting all test tasks\n");
        DPRINTF("Stopping task 1\n");
        task1.stop();
        DPRINTF("Stopping task 2\n");
        task2.stop();
        DPRINTF("Stopping task 3\n");
        task3.stop();
        DPRINTF("Stopping task 4\n");
        task4.stop();
        CPPUNIT_ASSERT_EQUAL(true, task_terminated);

        /* Check the counters to see if the counts match. Allow some variance
         * to account for the imprecision of halting the task based on a
         * timer.
         */
        CPPUNIT_ASSERT((counter[1] >= 48) && (counter[1] <= 60));
        CPPUNIT_ASSERT((counter[2] >= 48) && (counter[2] <= 60));
        CPPUNIT_ASSERT((counter[3] >= 98) && (counter[3] <= 110));
        CPPUNIT_ASSERT((counter[4] >= 23) && (counter[4] <= 35));

        /* Check that the runtimes are reasonable.
         */
        last_runtime = task1.get_last_runtime();
        IPRINTF("last_runtime = %" PRId64 "\n", int64_t(last_runtime));
        CPPUNIT_ASSERT(last_runtime > units::Nanoseconds(0));
        CPPUNIT_ASSERT(task1.get_max_runtime() >= last_runtime);
    }
コード例 #23
0
ファイル: CharmDataModelTests.cpp プロジェクト: hefee/Charm
void CharmDataModelTests::addAndRemoveTasksTest()
{   // set up a structure of tasks:
    Task task1( 1000, "Task 1" );
    Task task1_1( 1001, "Task 1-1", task1.id() );
    Task task1_2( 1002, "Task 1-2", task1.id() );
    Task task1_3( 1003, "Task 1-3", task1.id() );
    Task task2( 2000, "Task 2" );
    Task task2_1( 2100, "Task 2-1", task2.id() );
    Task task2_1_1( 2110, "Task 2-1-1", task2_1.id() );
    Task task2_1_2( 2120, "Task 2-1-2", task2_1.id() );
    Task task2_2( 2200, "Task 2-2", task2.id() );
    Task task2_2_1( 2210, "Task 2-2-1", task2_2.id() );
    Task task2_2_2( 2220, "Task 2-2-2", task2_2.id() );

    // set up a data model, and add all the tasks to it, step by step:
    CharmDataModel model;
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 0 );
    model.addTask( task1 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 1 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 0 );
    model.addTask( task1_1 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 1 );
    model.addTask( task1_2 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 2 );
    model.addTask( task1_3 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 1 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 3 );
    model.addTask( task2 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 2 );
    model.addTask( task2_1 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 1 );
    model.addTask( task2_2 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );
    QVERIFY( model.taskTreeItem( task2_1.id() ).childCount() == 0 );
    model.addTask( task2_1_1 );
    QVERIFY( model.taskTreeItem( task2_1.id() ).childCount() == 1 );
    model.addTask( task2_1_2 );
    QVERIFY( model.taskTreeItem( task2_1.id() ).childCount() == 2 );
    QVERIFY( model.taskTreeItem( task2_2.id() ).childCount() == 0 );
    model.addTask( task2_2_1 );
    QVERIFY( model.taskTreeItem( task2_2.id() ).childCount() == 1 );
    model.addTask( task2_2_2 );
    QVERIFY( model.taskTreeItem( task2_2.id() ).childCount() == 2 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );

    // now the whole game in reverse: remove tasks, one by one:
    model.deleteTask( task2_2_2 );
    QVERIFY( model.taskTreeItem( task2_2.id() ).childCount() == 1 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );
    model.deleteTask( task2_2_1 );
    QVERIFY( model.taskTreeItem( task2_2.id() ).childCount() == 0 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );
    model.deleteTask( task2_1_1 );
    QVERIFY( model.taskTreeItem( task2_1.id() ).childCount() == 1 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );
    model.deleteTask( task2_1_2 );
    QVERIFY( model.taskTreeItem( task2_1.id() ).childCount() == 0 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 2 );
    model.deleteTask( task2_2 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 1 );
    model.deleteTask( task2_1 );
    QVERIFY( model.taskTreeItem( task2.id() ).childCount() == 0 );
    model.deleteTask( task2 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 1 );
    model.deleteTask( task1_2 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 2 );
    model.deleteTask( task1_3 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 1 );
    model.deleteTask( task1_1 );
    QVERIFY( model.taskTreeItem( task1.id() ).childCount() == 0 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 1 );
    model.deleteTask( task1 );
    QVERIFY( model.taskTreeItem( 0 ).childCount() == 0 );
}
コード例 #24
0
ファイル: mainwindow.cpp プロジェクト: zassyne/SimpleProject
MainWindow::MainWindow(QWidget *parent) :

    QMainWindow(parent),

    ui(new Ui::MainWindow)

{

    ui->setupUi(this);

    this->setFixedSize(400, 200);

    bouton = new QPushButton("Find", this);

    layout = new QHBoxLayout;

    zone1  = new QTextEdit(this);

    zone2  = new QTextEdit(this);

    zone3  = new QTextEdit(this);

    erase  = new QPushButton("clear", this);

    msgBox = new QMessageBox(this);

    msgBox->setText("Erreur...");

    msgBox->setStandardButtons(QMessageBox::Ok);

    msgBox->setIcon(QMessageBox::Warning);

    msgBox->setWindowTitle("Erreur...");

    erase->setVisible(false);

    zone3->setReadOnly(true);

    layout->addWidget(bouton);

    layout->addWidget(zone1);

    layout->addWidget(zone2);

    layout->addWidget(zone3);



    const int w_bouton = 60;

    const int h_bouton = 20;

    const int w_zone = 80;

    const int h_zone = 25;





    bouton->setFixedSize(w_bouton, h_bouton);

    erase->setFixedSize(w_bouton, h_bouton);

    zone1->setFixedSize(w_zone, h_zone);

    zone2->setFixedSize(w_zone, h_zone);

    zone3->setFixedSize(w_zone, h_zone);



    bouton->move(220, 60);

    erase->move(220, 60);

    zone1->move(20, 60);

    zone2->move(120, 60);

    zone3->move(300, 60);



    connect(bouton, SIGNAL(clicked()), this, SLOT(task()));

    connect(erase, SIGNAL(clicked()), this, SLOT(task2()));

}
コード例 #25
0
//
//  a task gets dispatched on every tick_flag tick (10ms)
//
void task_dispatch(void)
{
  /* scan the task bits for an active task and execute it */

  char task;
    

/* take care of the task timers. if the value ==0 skip it
    else decrement it. If it decrements to zero, activate the task associated with it */

  task=0;
  while (task < NUM_TASKS )
    {
    if (task_timers[task])
       {
       task_timers[task]--;            /* dec the timer */
       if (task_timers[task] == 0 )
            {
            set_task(task); /* if ==0 activate the task bit */
            }
       }
    task++;
    }

  task = 0; /* start at the most significant task */
  while (task <= NUM_TASKS )
    {
      if ((task_bits & pgm_read_byte(&bit_mask[task])))
            {
            break; /* if activate task found..*/
            }
      task++;         /* else try the next one */
    }
  switch(task)            /* if task bit is active..execute the task */
    {
    case 0:
      task0();
      break;
    case 1:
      task1();
      break;
    case 2:
      task2();
      break;
    case 3:
      task3();
      break;
    case 4:
      task4();
      break;
    case 5:
      task5();
      break;
    case 6:
      task6();
      break;
    case 7:
      task7();
      break;
    default:
      break;                  /* no task was active!! */
    }                       
}
コード例 #26
0
/*IRQ Handler*/
void __attribute__((interrupt)) do_irq()
{
    task2();
    *(volatile unsigned long *)(CONFIG_SYS_TIMERBASE + 0x0C) = 1; // clear the timer interrupt
}
コード例 #27
0
void
PriorityTapeGroupTest::testSchedule()
{
    auto_ptr<PriorityTape> priority0(new PriorityTape());
    auto_ptr<PriorityTape> priority1(new PriorityTape());
    auto_ptr<PriorityTape> priority2(new PriorityTape());
    auto_ptr<PriorityTape> priority3(new PriorityTape());

    PriorityTapeTask task0(priority0.get(),10,0,1);
    PriorityTapeTask task1(priority1.get(),10,0,1);
    PriorityTapeTask task2(priority2.get(),10,0,1);
    PriorityTapeTask task3(priority3.get(),10,0,1);

    vector<string> tapes;
    tapes.push_back("01000001");
    tapes.push_back("01000002");
    tapes.push_back("02000001");
    tapes.push_back("02000002");

    vector<PriorityTape *> priorities;
    priorities.push_back(priority0.get());
    priorities.push_back(priority1.get());
    priorities.push_back(priority2.get());
    priorities.push_back(priority3.get());

    auto_ptr<PriorityTapeGroup> group(new PriorityTapeGroup(tapes,priorities));


    task0.Start();
    task1.Start();
    task2.Start();
    task3.Start();
    boost::this_thread::sleep(
            boost::posix_time::milliseconds(10) );
    CPPUNIT_ASSERT( false == task0.Finished() );
    CPPUNIT_ASSERT( false == task1.Finished() );
    CPPUNIT_ASSERT( false == task2.Finished() );
    CPPUNIT_ASSERT( false == task3.Finished() );


    group->Enable(true);

    task0.Start();
    task1.Start();
    task2.Start();
    task3.Start();
    boost::this_thread::sleep(
            boost::posix_time::milliseconds(10) );
    CPPUNIT_ASSERT( true == task0.Finished() );
    CPPUNIT_ASSERT( true == task1.Finished() );
    CPPUNIT_ASSERT( true == task2.Finished() );
    CPPUNIT_ASSERT( true == task3.Finished() );


    group->Enable(false);

    task0.Start();
    task1.Start();
    task2.Start();
    task3.Start();
    boost::this_thread::sleep(
            boost::posix_time::milliseconds(10) );
    CPPUNIT_ASSERT( false == task0.Finished() );
    CPPUNIT_ASSERT( false == task1.Finished() );
    CPPUNIT_ASSERT( false == task2.Finished() );
    CPPUNIT_ASSERT( false == task3.Finished() );


    boost::posix_time::ptime begin =
            boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( false == group->Request(false,10,0) );
    boost::posix_time::ptime end =
            boost::posix_time::microsec_clock::local_time();
    int duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );


    group->Enable(true);

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( false == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration >= 10 && duration <= 12 );
    CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );

    group->Release(false);

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    group->Release(false);


    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(true,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(true,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( false == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
            duration >= 10 && duration <= 12 );
    CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );

    group->Release(true);

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( false == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );

    group->Release(false);

    begin = boost::posix_time::microsec_clock::local_time();
    CPPUNIT_ASSERT( true == group->Request(false,10,0) );
    end = boost::posix_time::microsec_clock::local_time();
    duration = (end - begin).total_milliseconds();
    CPPUNIT_ASSERT( duration <= 5 );

    group->Release(true);

    group->Release(false);
}
コード例 #28
0
ファイル: a.c プロジェクト: NurlashKO/Labs
int main() {
  printf("Variant C\n");
  printf("Is it possible to read and write using only O_APPEND flag : %s\n", task1());
  printf("Is it possible to read from arbitrary position in the file using lseek() : %s\n", task2());
  printf("Is it possible to use lseek to change data in arbitrary position : %s\n", task3());
}
コード例 #29
0
ファイル: thread2.c プロジェクト: rozmov/RavenOS
/*! 
    \brief Thread definition for thread 2.
    \param argument A pointer to the list of arguments.
*/
void thread2 (void const *argument) 
{
  if (addTraceProtected("thread2 start run") != TRACE_OK)
	{
		stop_cpu;
	}
	
  while (1) 
	{		
		if (addTraceProtected("thread2 take sem0 attempt") != TRACE_OK)
		{
			stop_cpu;
		}		
    if ( osSemaphoreWait (sid_Semaphore0, osWaitForever) != -1 ) // wait forever
		{					 
			if (addTraceProtected("thread2 take sem0 success") != TRACE_OK)
			{
				stop_cpu;
			}	
			
			task2(); // thread code
			count1Sec();
			task2();
			
			if (addTraceProtected("thread2 release sem0 attempt") != TRACE_OK)
			{
				stop_cpu;
			}				
			if (osSemaphoreRelease (sid_Semaphore0) != osOK)
			{
				if (addTraceProtected("thread2 release sem0 fail") != TRACE_OK)
				{
					stop_cpu;
				}						
			}
		}
		else
		{
			if (addTraceProtected("thread2 take sem0 fail") != TRACE_OK)
			{
				stop_cpu;
			}				
		}

		if (addTraceProtected("thread2 set priority to osPriorityBelowNormal") != TRACE_OK)
		{
			stop_cpu;
		}		
		osThreadSetPriority(osThreadGetId(), osPriorityBelowNormal);
		
		if (addTraceProtected("thread2 yields") != TRACE_OK)
		{
			stop_cpu;
		}		
    osThreadYield();                                            // suspend thread
		
		if (addTraceProtected("thread2 back from yield") != TRACE_OK)
		{
			stop_cpu;
		}
		
		// This should terminate the current thread2 thread		
		if (Terminate_thread2() != 0)
		{
			stop_cpu;		
		}
		
  }
}
コード例 #30
0
ファイル: client.cpp プロジェクト: Yijtx/ACE
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
    {

      // Initialize orb
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

      // Resolve HomeFinder interface
      CORBA::Object_var obj1
        = orb->string_to_object (ior1);

      CORBA::Object_var obj2
        = orb->string_to_object (ior2);

      CORBA::Object_var obj3
        = orb->string_to_object (ior3);

      CORBA::Object_var obj4
        = orb->string_to_object (ior4);

      if (CORBA::is_nil (obj1.in ()) ||
          CORBA::is_nil (obj2.in ()) ||
          CORBA::is_nil (obj3.in ()) ||
          CORBA::is_nil (obj4.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Nil Benchmark::RoundtripClient reference\n"),
                            1);
        }

      //Narrow to appropriate interfaces
      Benchmark::RoundTripClient_var client1=
        Benchmark::RoundTripClient::_narrow (obj1.in());

      Benchmark::RoundTripClient_var client2=
        Benchmark::RoundTripClient::_narrow (obj1.in());

      Benchmark::RoundTripClient_var client3=
        Benchmark::RoundTripClient::_narrow (obj1.in());

      Benchmark::RoundTripClient_var client4=
        Benchmark::RoundTripClient::_narrow (obj1.in());

      //Create Tasks
      Client_Task task1(client1.in());
      Client_Task task2(client2.in());
      Client_Task task3(client3.in());
      Client_Task task4(client4.in());

      task1.activate(THR_NEW_LWP | THR_JOINABLE);
      task2.activate(THR_NEW_LWP | THR_JOINABLE);
      task3.activate(THR_NEW_LWP | THR_JOINABLE);
      task4.activate(THR_NEW_LWP | THR_JOINABLE);

      task1.thr_mgr()->wait();
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception Caught:");
      return 1;
    }
  return 0;
}