Example #1
0
void *Task::workerLoop(void *aux){
	ThreadData *data = (ThreadData *)aux;
	while (1){
		pthread_mutex_lock(&(data->mutex)); 
			while (data->t == NULL){
				pthread_cond_wait(&(data->todo), &(data->mutex)); 
			}
		Task* task = data->t;
		pthread_mutex_unlock(&(data->mutex)); 
		pthread_mutex_lock(&(task->lock));
		task->started = true; 
		pthread_mutex_unlock(&(task->lock));
		if (task->getType() == TASK_EXITER){
			data->status = THREAD_KILLED;
		}
		task->run();
		pthread_mutex_lock(&(task->lock));
		task->finished = true;
		pthread_cond_broadcast(&(task->wait)); 
		pthread_mutex_unlock(&(task->lock));
		data->status = THREAD_WAITING;
		data->parent->notifyDone(data);
	} 
	return NULL;  
}
  void TaskSchedulerSys::run(size_t threadIndex, size_t threadCount)
  {
    while (true)
    {      
      /* wait for available task */
      mutex.lock();
      while ((end-begin) == 0 && !terminateThreads) {
        condition.wait(mutex); continue;
      }
      
      /* terminate this thread */
      if (terminateThreads) {
        mutex.unlock(); return;
      }

      /* take next task from stack */
      size_t i = (end-1)&(tasks.size()-1);
      Task* task = tasks[i]; 
      size_t elt = --task->started;
      if (elt == 0) end--;
      mutex.unlock();
      
      /* run the task */
      TaskScheduler::Event* event = task->event;
      thread2event[threadIndex] = event; 
      if (task->run) task->run(task->runData,threadIndex,threadCount,elt,task->elts,task->event);
      
      /* complete the task */
      if (--task->completed == 0) {
        if (task->complete) task->complete(task->completeData,threadIndex,threadCount,task->event);
        if (event) event->dec();
      } 
    }
  }
Example #3
0
void ResourceManager::decodeResource( ResourceLoadOptions& options )
{
	Task* task = Allocate(GetResourcesAllocator(), Task);
	
	ResourceLoadOptions* taskOptions = Allocate(GetResourcesAllocator(),
		ResourceLoadOptions);

	*taskOptions = options;

	task->callback.Bind(ResourceTaskRun);
	task->userdata = taskOptions;

	numResourcesQueuedLoad.increment();

#ifdef ENABLE_THREADED_LOADING
	if( taskPool && asynchronousLoading && options.asynchronousLoad )
	{
		taskPool->add(task, options.isHighPriority);
		return;
	}
#endif

	task->run();
	sendPendingEvents();
}
Example #4
0
    void ThreadPool::taskEntry() {
        {
            boost::unique_lock<boost::mutex> lk(mStartMutex);
            while(!mStartWork) {
                mStartCondition.wait(lk);
            }
        }

        while(true) {
            Task* task = NULL;
            {
                boost::lock_guard<boost::mutex> lk(mTaskQueueMutex);
                if(mTasks.size() == 0) {
                    break;
                }
                task= mTasks.back();
                mTasks.pop_back();
            }

            if(task) {
                task->run();
            }

            {
                boost::unique_lock<boost::mutex> lk(mTaskQueueMutex);
                if(--mTasksNum == 0) {
                    mTasksCondition.notify_all();
                    break;
                }
            }

        }
    }
Example #5
0
int main()
{
    Task task;
    task.run(ctx_function);
    Task task2;
    int x = 11;
    task2.run([x]{std::cout << "Hello from lambda: x = " << x << "\n";});
    Task con_task2;
    con_task2.run(ctx_function);
    Task con_task3;
    con_task3.run(ctx_function);
    Task con_task4;
    con_task4.run(ctx_function);

    Task con_task10;
    con_task10.run(ctx_function2);
    std::cout << "Returned to fcm after run\n";
    con_task10.wait();
    Task con_task11;
    con_task11.run(::std::bind(ctx_arg1, 0));
    Task con_task12;
    con_task12.run(::std::bind(ctx_arg1, 11));

    Task::yield();
    std::cout << "Returned to main\n";
    con_task2.wait();
    return 0;
}
Example #6
0
static void *task_scheduler_thread_run(void *thread_p)
{
	TaskThread *thread = (TaskThread *) thread_p;
	TaskScheduler *scheduler = thread->scheduler;
	int thread_id = thread->id;
	Task *task;

	/* keep popping off tasks */
	while (task_scheduler_thread_wait_pop(scheduler, &task)) {
		TaskPool *pool = task->pool;

		/* run task */
		task->run(pool, task->taskdata, thread_id);

		/* delete task */
		if (task->free_taskdata)
			MEM_freeN(task->taskdata);
		MEM_freeN(task);

		/* notify pool task was done */
		task_pool_num_decrease(pool, 1);
	}

	return NULL;
}
Example #7
0
void TaskThread::run()
{
#ifdef THREAD_DEBUG
	printf("TaskThread %p running\n", this);
#endif
	do {
#ifdef THREAD_DEBUG
		printf("TaskThread %d sleeping...\n", mIndex);
#endif
		mSema.wait();
#ifdef THREAD_DEBUG
		printf("TaskThread %d woke up -- running task loop\n", mIndex);
#endif
		Task *task;
		while ((task = getATask()) != NULL) {
#ifdef THREAD_DEBUG
            printf("TaskThread %d running task %p...\n", mIndex, task);
#endif
			task->run();
#ifdef THREAD_DEBUG
            printf("TaskThread %d task %p done\n", mIndex, task);
#endif
			delete task;
		}
		notify();
	}
	while (!mStopping);
#ifdef THREAD_DEBUG
	printf("TaskThread %p exiting\n", this);
#endif
}
Example #8
0
/**
 * Static class member that actually runs the target task.
 *
 * The code here will run on the task thread.
 * @param [in] pTaskInstance The task to run.
 */
void Task::runTask(void* pTaskInstance) {
	Task* pTask = (Task*) pTaskInstance;
	ESP_LOGD(LOG_TAG, ">> runTask: taskName=%s", pTask->m_taskName.c_str());
	pTask->run(pTask->m_taskData);
	ESP_LOGD(LOG_TAG, "<< runTask: taskName=%s", pTask->m_taskName.c_str());
	pTask->stop();
} // runTask
Example #9
0
void Worker::
        loop_while_tasks()
  {
    while (!QThread::currentThread ()->isInterruptionRequested ())
      {
        Task task;

        {
            DEBUGINFO TaskTimer tt(boost::format("worker: get task %s %s") % vartype(*schedule_.get ()) % (computing_engine_?vartype(*computing_engine_):"(null)") );
            task = schedule_->getTask(computing_engine_);
        }

        if (task)
          {
            DEBUGINFO TaskTimer tt(boost::format("worker: running task %s") % task.expected_output());
            task.run();
            emit oneTaskDone();
          }
        else
          {
            DEBUGINFO TaskInfo("worker: back to sleep");
            // Wait for a new wakeup call
            break;
          }
      }
  }
void Executer::doRun(){
    
    if(atomic_load(&m_state) != EXECUTER_STATE_STARTED){
        return;
    }
    
    for(;;){
        if(m_task_queue->isEmpty()){
            // just sleep
            usleep(1000);
            continue;
        }
        
        
        Task t = m_task_queue->wait_to_take();
        t.run();
        
        if(atomic_load(&m_state) == EXECUTER_STATE_SHUTTINGDOWN){
            if(m_task_queue->isEmpty()){
                atomic_store(&m_state, EXECUTER_STATE_SHUTDOWN);
                return;
            }
        }
        
    }
}
Example #11
0
int main()
{
    Task::yield();
    Task task;
    task.run(ctx_function2);
    Task task2;
    task2.run(ctx_function2);
    return 0;
}
int main()
{
    Task task;
    task.run(ctx_function);
    Task task2;
    int x = 11;
    task2.run([x]{std::cout << "Hello from lambda: x = " << x << "\n";});
    return 0;
}
Example #13
0
int routine(void *data) {
    while (true) {
        SDL_LockMutex(threadLock);
        SDL_CondWait(taskAvailable, threadLock);
        Task* task = tasks.front();
        tasks.pop();
        task->run();
        delete task;
        SDL_UnlockMutex(threadLock);
    }
    return 0;
}
Example #14
0
    void process(device_data* device) {
        xlog("GetEventSender");
        if(device->last_event_id > device->current_event_id) {
                //check and amend difference between current and last event id if exists
                if(device->last_event_id - device->current_event_id > DEVICE_EVENT_CASH) {
                        device->current_event_id = device->last_event_id - DEVICE_EVENT_CASH;
                }

                if(!findTask2(device->addr)) {
                    Task* task = new GetEventsTask(device);
                    addTask2(device->addr,task);
                    task->run();
                }
        }
    }
Example #15
0
    void Thread::thread_loop() {
        Task *task;

        threadStarted();

        while(_run) {
            try {
                while ((task = getNextTask())) {
                    task->run();
                    task->acquired_thread = 0;
                    if (task->task_finished)
                        delete task;
                }
                
                while ((task = dynamic_cast<Task*>(Task::getNextTask()))) {
                    task->run();
                    task->acquired_thread = 0;
                    if (task->task_finished)
                        delete task;
                }
                
                if (task_queue.length())
                    continue;
                
            } catch (...) {
                LOG(Log::LOGLEVEL_ERROR, "Invalid Task in queue");
            }
            
            if (!pool || threads->length() > max_threads)
                break;
            
            wait();
        }

        threadFinished();
    }
void *TaskQueue::process(void *task_queue_ptr) {
    TaskQueue *task_queue = static_cast<TaskQueue*> (task_queue_ptr);
    while (1) {
        Task *t = task_queue->get();
      //  Logger::debug("TaskQueue::process() got task");
        try {
            t->run();
        } catch (std::exception &ex) {
            Logger::error("TaskQueue::process() %s", ex.what());
        //    throw;
        }
        //Logger::debug("TaskQueue::process() finished task");
        delete t;
    }
    return NULL;
}
Example #17
0
void *
task_pth_run(void *data)
{
   Task *task;

   task = (Task *) data;
   char msgPortName[10];

   pth_msgport_t mp;

   pth_event_t ev;

#ifdef _LDEBUG
   printf("F=%s,L=%d,data_pth_run=%p,%p,name=%s,%p\n", __FILE__, __LINE__, data, task, task->name, task->name);
#endif
   if (task == NULL)
      return NULL;
   append_List(&Tasks, (void *) task);
   local_print_List(&Tasks);

   snprintf(msgPortName, 10, "%ld", task->id);
#ifdef _MDEBUG
   printf("F=%s,L=%d,task->id=%ld,msgPortName=%s\n", __FILE__, __LINE__, task->id, msgPortName);
#endif
   mp = pth_msgport_create(msgPortName);
   ev = pth_event(PTH_EVENT_MSG, mp);

   if (task->run)
      task->run(task->data);

   pth_event_free(ev, PTH_FREE_THIS);
   pth_msgport_destroy(mp);

   if (task->destroy)
      task->destroy(task->data);
   stopcount = 0;
   Task_START();
   removeIt_List(&Tasks, task);
//      local_print_List(&Tasks);
   free(task->name);
   free(task);
#ifdef _LDEBUG
   printf("	task end run=%p\n", task);
   printf("F=%s,L=%d\n", __FILE__, __LINE__);
#endif
   return NULL;
}
Example #18
0
void TaskPool::run(Thread* thread, void* userdata)
{

    while (!isStopping && (!tasks.empty() || !isWaiting))
    {
        Task* task;
        tasks.wait_and_pop_front(task);

        if (!task) continue;

        pushEvent(task, TaskState::Started );

        task->run();
        
        pushEvent(task, TaskState::Finished );
    }
}
Example #19
0
void* ThreadPool::execute_thread()
{
    Task* task = NULL;
    LOG_DEBUG("Starting thread :%u", pthread_self());
    while(true) {
        // Try to pick a task
        LOG_DEBUG("Locking: %u", pthread_self());
        m_task_mutex.lock();

        // We need to put pthread_cond_wait in a loop for two reasons:
        // 1. There can be spurious wakeups (due to signal/ENITR)
        // 2. When mutex is released for waiting, another thread can be waken up
        //    from a signal/broadcast and that thread can mess up the condition.
        //    So when the current thread wakes up the condition may no longer be
        //    actually true!
        while ((m_pool_state != STOPPED) && (m_tasks.empty())) {
            // Wait until there is a task in the queue
            // Unlock mutex while wait, then lock it back when signaled
            LOG_DEBUG("Unlocking and waiting: %u", pthread_self());
            m_task_cond_var.wait(m_task_mutex.get_mutex_ptr());
            LOG_DEBUG("Signaled and locking: %u", pthread_self());
        }

        // If the thread was woken up to notify process shutdown, return from here
        if (m_pool_state == STOPPED) {
            LOG_DEBUG("Unlocking and exiting: %u", pthread_self());
            m_task_mutex.unlock();
            pthread_exit(NULL);
        }

        task = m_tasks.front();
        m_tasks.pop_front();
        LOG_DEBUG("Unlocking: %u", pthread_self());
        m_task_mutex.unlock();

        //cout << "Executing thread " << pthread_self() << endl;
        // execute the task
        task->run(); //
        //cout << "Done executing thread " << pthread_self() << endl;
        delete task;
    }
    return NULL;
}
Example #20
0
VOID Simulator::startScheduler()
{
   LOG_ENTERFN();

   for (;;)
   {
      getMilliSeconds();
      if (KB_KEY_SIM_QUIT == Keyboard::key)
      {
         LOG_INFO("Exiting Simulator");
         break;
      }

      if (Keyboard::key != KB_KEY_PAUSE_TRAFFIC)
      {
         TaskMgr::resumePausedTasks();
      }

      TaskList *pRunningTasks = TaskMgr::getRunningTasks();
      TaskListItr itr = pRunningTasks->begin();
      while (itr != pRunningTasks->end())
      {
         Task *t = *itr;

         // increment the iterator here, because after the task is run
         // it will be paused state which will move the task from running
         // task list to paused task list.
         itr++;
         if (ROK != t->run())
         {
            t->abort();
         }
      }

      getMilliSeconds();

      // read the sockets for keyboard events and gtp messages
      socketPoll(1);
   }
 
   LOG_EXITVOID();
}
Example #21
0
 void TaskSchedulerSys::work(size_t threadIndex, size_t threadCount, bool wait)
 {
   /* wait for available task */
   mutex.lock();
   while ((end-begin) == 0 && !terminateThreads) {
     if (wait) condition.wait(mutex);
     else { mutex.unlock(); return; }
   }
   
   /* terminate this thread */
   if (terminateThreads) {
     mutex.unlock();
     throw TaskScheduler::Terminate();
   }
   
   /* take next task from stack */
   size_t i = (end-1)&(tasks.size()-1);
   Task* task = tasks[i]; 
   size_t elt = --task->started;
   if (elt == 0) end--;
   mutex.unlock();
   
   /* run the task */
   TaskScheduler::Event* event = task->event;
   thread2event[threadIndex].event = event; 
   if (task->run) {
     size_t taskID = TaskLogger::beginTask(threadIndex,task->name,elt);
     task->run(task->runData,threadIndex,threadCount,elt,task->elts,task->event);
     TaskLogger::endTask(threadIndex,taskID);
   }
   
   /* complete the task */
   if (--task->completed == 0) {
     if (task->complete) {
       size_t taskID = TaskLogger::beginTask(threadIndex,task->name,0);
       task->complete(task->completeData,threadIndex,threadCount,task->event);
       TaskLogger::endTask(threadIndex,taskID);
     }
     if (event) event->dec();
   }
 }
Example #22
0
void TaskSys::threadFct() 
{
    int myIndex = 0; //lAtomicAdd(&threadIdx,1);
    while (1) {
        while (!taskQueue[myIndex].active) {
#ifndef ISPC_IS_KNC
            usleep(4);
#else
            _mm_delay_32(32);
#endif
            continue;
        }

        Task *mine = taskQueue[myIndex].task;
        while (!mine->noMoreWork()) {
            int job = mine->nextJob();
            if (job >= mine->numJobs()) break;
            mine->run(job,myIndex);
        }
        taskQueue[myIndex].doneWithThis();
        myIndex = (myIndex+1)%MAX_LIVE_TASKS;
    }
}
Example #23
0
  /** Thread method. Will wait for new tasks and run them
   * as scheduled to it.
   */
  void ThreadPoolRunnable::run()
  {
    Task * task;

    // If there are no tasks yet, wait up to m_waitSec for them to come up
    while (m_scheduler->size() == 0 && m_waitSec > 0.0)
    {
      Poco::Thread::sleep(10); // millisec
      m_waitSec -= 0.01; // Subtract ten millisec from the time left to wait.
    }

    while (m_scheduler->size() > 0)
    {
      // Request the task from the scheduler.
      // Will be NULL if not found.
      task = m_scheduler->pop(m_threadnum);

      if (task)
      {
        //Task-specific mutex if specified?
        Mutex * mutex = task->getMutex();
        if (mutex)
          mutex->lock();

        try
        {
          // Run the task (synchronously within this thread)
          task->run();
        }
        catch (std::exception &e)
        {
          // The task threw an exception!
          // This will clear out the list of tasks, allowing all threads to finish.
          m_scheduler->abort(std::runtime_error(e.what()));
        }

        // Tell the scheduler that we finished this task
        m_scheduler->finished(task, m_threadnum);

        // Report progress, if specified.
        if (m_prog)
          m_prog->report();

        // Unlock the mutex, if any.
        if (mutex)
          mutex->unlock();

        // We now delete the task to free up memory
        delete task;
      }
      else
      {
        // No appropriate task for this thread (perhaps a mutex is locked)
        // but there are more tasks.
        // So we wait a bit before checking again.
        Poco::Thread::sleep(10); // millisec
      }
    }
    // Ran out of tasks that could be run.
    // Thread now will exit
  }
Example #24
0
void ThreadPool::processTasks(int procType, int tid)
{
	// Inform that this threads was created.
	//sem_post(&createdThreads);
	pthread_mutex_unlock(&createdThreads);

//	if(ExecEngineConstants::GPU == procType && gpuTempDataSize >0){
//		printf("GPU tid=%d allocDataSize=%d\n", tid, gpuTempDataSize);
//		gpuTempData[tid] = cudaMemAllocWrapper(gpuTempDataSize);
//	}

	fprintf(stderr,"procType:%d  tid:%d waiting init of execution\n", procType, tid);
	pthread_mutex_lock(&initExecutionMutex);
	pthread_mutex_unlock(&initExecutionMutex);

	Task *curTask = NULL;
	// ProcessTime example
	struct timeval startTime;
	struct timeval endTime;

	while(true){

		curTask = this->tasksQueue->getTask(procType);
		if(curTask == NULL){

			if(this->execEngine->getCountTasksPending() != 0 || this->execDone == false){
				usleep(1000);
				this->tasksQueue->incrementTasksToProcess();
				// All tasks ready to execute are finished, but there still existing tasks pending due to unsolved dependencies
				continue;

			}
			fprintf(stderr,"procType:%d  tid:%d Task NULL #t_pending=%d\n", procType, tid, this->execEngine->getCountTasksPending());
			break;
		}
		gettimeofday(&startTime, NULL);

		curTask->run(procType, tid);

		gettimeofday(&endTime, NULL);

		// Resolve dependencies pending.

		// calculate time in microseconds
		double tS = startTime.tv_sec*1000000 + (startTime.tv_usec);
		double tE = endTime.tv_sec*1000000  + (endTime.tv_usec);
		fprintf(stderr,"procType:%d  tid:%d Task speedup = %f procTime = %f\n", procType, tid, curTask->getSpeedup(), (tE-tS)/1000000);
		delete curTask;

	}

//	printf("Leaving procType:%d  tid:%d #t_pending=%d\n", procType, tid, this->execEngine->getCountTasksPending());
//	if(ExecEngineConstants::GPU == procType && gpuTempDataSize >0){
//		cudaFreeMemWrapper(gpuTempData[tid]);
//	}
	// I don't care about controlling concurrent access here. Whether two threads
	// enter this if, their resulting gettimeofday will be very similar if not the same.
	if(firstToFinish){
		firstToFinish = false;
		gettimeofday(&firstToFinishTime, NULL);
	}

	gettimeofday(&lastToFinishTime, NULL);
}
Example #25
0
void CppMain(void)
{
  Sheet *sht_back,*sht_mouse;
  Task *task_main;

  //-----------------------------------
  //もろもろの初期化(割り込み、キーボード、マウス)
  //----------------------------------
  Descriptor::Initialize();						
  Interrupt::Initialize();								
  Memory::Initialize();										
  fifo->Initialize(128,0);
  Keyboard::Initialize();										
  Mouse::Initialize();									
  TimerControl::Initialize();									
  SheetControl::Initialize();
  TaskControll::Initialize();			
  Graphic::Initialize();

  io_sti();			         //IDT/PICの初期化が終わったのでCPUの割り込みを許可する

  //-----------------------------------
  //メイン
  //-----------------------------------

  //背景シート
  sht_back  = SheetControl::alloc();	
  sht_back->setbuf(((struct BOOTINFO*)(ADR_BOOTINFO))->scrnx,
				   ((struct BOOTINFO*)(ADR_BOOTINFO))->scrny, -1);		
  sht_back->g->init_screen8();
  sht_back->slide(0, 0);						
  sht_back->updown(0);				

  //マウスシート
  sht_mouse = SheetControl::alloc();
  sht_mouse->setbuf(16, 16, 99);	
  sht_mouse->g->init_mouse_cursor8(99);							
  sht_mouse->updown(2);							
  sht_mouse->slide(Mouse::x, Mouse::y);	

  //メインタスク
  task_main = TaskControll::task_now();		
  fifo->task = task_main;			 
  task_main->run(1,0);                    //レベル1に切り変える

	
  //-----------------------------------
  //サブ
  //-----------------------------------

  //サブタスク
  Sheet *s[2];
  for(int i=0; i<2; i++){
	s[i] = SheetControl::alloc();
	s[i]->setbuf(256,165,-1);
	s[i]->g->make_window8((unsigned char*)"Terminal",1,1);
	s[i]->g->make_window8((unsigned char*)"Terminal",0,0);
	s[i]->g->make_textbox8(COLOR_WHITE);
	s[i]->updown(i+1);
	s[i]->slide(100*i+100,100);
  }

  for(int i=0; i<2; i++){
	Task *t;
	t = TaskControll::make_new_task(&task_console,s[i],(unsigned char*)"Terminal");
	t->run(2,i+1);
  }
	
  //ログインタスク
  Sheet *l;
  l = SheetControl::alloc();
  l->setbuf(((struct BOOTINFO*)(ADR_BOOTINFO))->scrnx,
			((struct BOOTINFO*)(ADR_BOOTINFO))->scrny, -1);		
  l->g->make_login8();
  l->updown(100);
  l->slide(0,0);
  Task *lt;
  lt = TaskControll::make_new_task(&task_login,l,(unsigned char*)"Login");
  lt->run(2,1);
  

  //これいるんかな
  sht_back->refresh(0,0,((struct BOOTINFO*)(ADR_BOOTINFO))->scrnx,48);


  //キーボードへ送信するためのFifoを初期化
  Keyboard::keycmd.Initialize(32,0);
  Keyboard::keycmd.put(KEYCMD_LED);         //はじめにkey_ledsを反映させておく
  Keyboard::keycmd.put(Keyboard::key_leds);

  //-----------------------------------
  //メインループ
  //-----------------------------------
  while(1){
	//キーボードへ送信する
	if(Keyboard::keycmd.status()>0 && Keyboard::keycmd_wait>0){
	  Keyboard::keycmd_wait = Keyboard::keycmd.get();
	  Keyboard::wait_KBC_sendready();
	  io_out8(PORT_KEYDAT,Keyboard::keycmd_wait);
	}

	//割り込みを禁止する
	io_cli();									

	//fifoに何も入っていないとき割り込みを許可する
	if (fifo->status()==0){
	  task_main->sleep();	//タスクを眠らす
	  io_sti();
	}

	else{
	  int i = fifo->get();
	  io_sti();					//割り込みを許可する

	  //-----キーボード-----
	  if (256<=i && i<=511) {
		//割込みを見せる
		char s[256];
		sprintf(s,"INT21 PS/2 Keyboard %X",i-256);
		sht_back->g->putfonts8_asc_sht(sht_back->bxsize-300,sht_back->bysize-20,COLOR_LGREEN,COLOR_WHITE,(unsigned char*)s,30);
			
		//shiftの情報を得る
		if(i-256==0x2a)          Keyboard::key_shift |= 1;
		else if(i-256==0x36)     Keyboard::key_shift |= 2;
		else if(i-256==0xaa)     Keyboard::key_shift &= ~1;
		else if(i-256==0xb6)     Keyboard::key_shift &= ~2;
		//ledsの情報
		if(i-256==0x3a){//capslock
		  Keyboard::key_leds ^= 4;
		  Keyboard::keycmd.put(KEYCMD_LED);
		  Keyboard::keycmd.put(Keyboard::key_leds);
		}
		else if(i-256==0x45){//numlock
		  Keyboard::key_leds ^= 2;
		  Keyboard::keycmd.put(KEYCMD_LED);
		  Keyboard::keycmd.put(Keyboard::key_leds);
		}
		else if(i-256==0x46){//scrolllock
		  Keyboard::key_leds ^= 1;
		  Keyboard::keycmd.put(KEYCMD_LED);
		  Keyboard::keycmd.put(Keyboard::key_leds);
		}
		//キーボードからの応答
		if(i-256==0xfa){
		  Keyboard::keycmd_wait=-1;
		}
		else if(i-256==0xfe){
		  Keyboard::wait_KBC_sendready();
		  io_out8(PORT_KEYDAT,Keyboard::keycmd_wait);
		}
		//通常文字
		if( i-256 < 0x80 && Keyboard::Decode(i-256)!=0){
		  TaskControll::active_task_for_user->fifo->put(Keyboard::Decode(i-256)+256);
		  //Statusタスクにも送る
		  int k;
		  for(k=0;k<TaskControll::task_num_for_user;k++){
			if(strcmp((char*)TaskControll::tasks_for_user[k]->title,"Status")==0  &&
			   TaskControll::tasks_for_user[k] != TaskControll::active_task_for_user){
			  TaskControll::tasks_for_user[k]->fifo->put(Keyboard::Decode(i-256)+256);
			}
		  }
		}
		//バックスペース
		else if(i-256==0x0E){
		  TaskControll::active_task_for_user->fifo->put(8+256); // baskspaceは8にする(ASCIIコードより)
		}
		//エンター
		else if(i-256==0x1c){
		  TaskControll::active_task_for_user->fifo->put(0x0A+256); // enterは0Aにする(ASCIIコードより)
		}
		//Tabキーでアクティブなウィンドウを切り替える
		else if(i-256==0x0f &&
				strcmp((char*)TaskControll::active_task_for_user->title,"Login")!=0){

		  //シートの高さ
		  Sheet *old_ = TaskControll::active_task_for_user->sheet;
		  Sheet *new_;
		  int i;
		  for(i=0;i<TaskControll::task_num_for_user;i++){
			if(TaskControll::tasks_for_user[i]->sheet == old_){
			  break;
			}
		  }
		  new_ = TaskControll::tasks_for_user[ (i+1)%TaskControll::task_num_for_user  ]->sheet;
		  int tmp = new_->height;
		  new_->updown(old_->height);
		  old_->updown(tmp);
		  //タスク
		  TaskControll::change_active_task_for_user((Task*)0);
		  for(int i=0;i<TaskControll::task_num_for_user;i++){
			Task *t = TaskControll::tasks_for_user[i];
			Sheet *s = t->sheet;
			if( t == TaskControll::active_task_for_user){
			  s->g->make_window8(t->title,1,0);
			}
			else{
			  s->g->make_window8(t->title,0,0);
			}
			s->refresh(0,0,s->bxsize,20);
		  }
		}
	  }
	  //-----マウス-----
	  else if (512<=i && i <= 767) {
		//割込みを見せる
		char s[256];
		sprintf(s,"INT2C Mouse %X",i-512);
		sht_back->g->putfonts8_asc_sht(sht_back->bxsize-300,sht_back->bysize-20,COLOR_LGREEN,COLOR_WHITE,(unsigned char*)s,30);

		//データが3バイトそろったとき
		if (Mouse::Decode(i-512) != 0) {
					
		  //再描画を含めてシートを移動させる
		  sht_mouse->slide(Mouse::x, Mouse::y); /* マウスの移動 sheet_refreshを含む */

		  //新たなタスクを作成する
		  if(Mouse::left&&!Mouse::old_left &&
			 strcmp((char*)TaskControll::active_task_for_user->title,"Login")!=0){
			int newx = (TaskControll::active_task_for_user->sheet->vx0+50)%((struct BOOTINFO*)(ADR_BOOTINFO))->scrnx;
			int newy = (TaskControll::active_task_for_user->sheet->vx0+50)%((struct BOOTINFO*)(ADR_BOOTINFO))->scrny;
			if( 0 < Mouse::x-Mouse::moveX && Mouse::x-Mouse::moveX < 100	&& //terminal
				0 < Mouse::y-Mouse::moveY && Mouse::y-Mouse::moveY < 20){

			  Sheet *s = SheetControl::alloc();
			  s->setbuf(256,165,-1);
			  s->g->make_window8((unsigned char*)"Terminal",1,1);
			  s->g->make_window8((unsigned char*)"Terminal",0,0);
			  s->g->make_textbox8(COLOR_WHITE);
			  s->updown( TaskControll::active_task_for_user->sheet->height+1);
			  s->slide(newx,newy);
			  Task *t;
			  t = TaskControll::make_new_task(&task_console,s,(unsigned char*)"Terminal");
			  t->run(2,8);

			}
			if( 100 < Mouse::x-Mouse::moveX && Mouse::x-Mouse::moveX < 200	&& //status
				0 < Mouse::y-Mouse::moveY && Mouse::y-Mouse::moveY < 20){

			  Sheet *sheet_status;
			  sheet_status = SheetControl::alloc();
			  sheet_status->setbuf(600,300,-1);
			  sheet_status->g->make_window8((unsigned char*)"Status",1,1);
			  sheet_status->g->make_window8((unsigned char*)"Status",0,0);
			  sheet_status->g->make_textbox8(COLOR_WHITE);
			  sheet_status->updown( TaskControll::active_task_for_user->sheet->height+1);
			  sheet_status->slide(newx,newy);
			  Task* t_status = TaskControll::make_new_task(&task_status,sheet_status,(unsigned char*)"Status");
			  t_status->run(2,1);

			}
		  }

		  //アクティブなタスクを切り替える
		  if(Mouse::left&&!Mouse::old_left &&
			 strcmp((char*)TaskControll::active_task_for_user->title,"Login")!=0){
			int i;
			char isChange=0;
			//クリックしたタスクを探す
			for(i=0;i<TaskControll::task_num_for_user;i++){
			  Task* t = TaskControll::tasks_for_user[i];
			  Sheet *s = t->sheet;
			  if( s->vx0 < Mouse::x-Mouse::moveX && Mouse::x-Mouse::moveX < s->vx0+s->bxsize	&&
				  s->vy0 < Mouse::y-Mouse::moveY && Mouse::y-Mouse::moveY < s->vy0+s->bysize){
				isChange = 1;
				break;
			  }
			}
			//実際の切り替え
			if(isChange==1){
			  //シートの高さ
			  Sheet *old_ = TaskControll::active_task_for_user->sheet;
			  Sheet *new_ = TaskControll::tasks_for_user[i]->sheet;
			  int tmp = new_->height;
			  new_->updown(old_->height);
			  old_->updown(tmp);
			  //タスク
			  TaskControll::change_active_task_for_user(TaskControll::tasks_for_user[i]);
			  for(int i=0;i<TaskControll::task_num_for_user;i++){
				Task *t = TaskControll::tasks_for_user[i];
				Sheet *s = t->sheet;
				if( t == TaskControll::active_task_for_user){
				  s->g->make_window8(t->title,1,0);
				}
				else{
				  s->g->make_window8(t->title,0,0);
				}
				s->refresh(0,0,s->bxsize,20);
			  }
			}
		  }
		  //移動する
		  if (Mouse::left&&Mouse::old_left &&
			  strcmp((char*)TaskControll::active_task_for_user->title,"Login")!=0){
			Sheet *t = TaskControll::active_task_for_user -> sheet;
			if( t->vx0 < Mouse::x-Mouse::moveX && Mouse::x-Mouse::moveX < t->vx0+t->bxsize	&&
				t->vy0 < Mouse::y-Mouse::moveY && Mouse::y-Mouse::moveY < t->vy0+t->bysize
				)	
			  {
				int newx = t->vx0+Mouse::moveX;
				int newy = t->vy0+Mouse::moveY;
				struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO;

				if(newx + t->bxsize<5)				{ newx = -t->bxsize+5;}
				if(newx > binfo->scrnx-5)					{ newx = binfo->scrnx-5;}
				if(newy + t->bysize<5)				{ newy = -t->bysize+5;}
				if(newy > binfo->scrny-5)					{ newy = binfo->scrny-5;}


				t->slide(newx,newy);

			  }
		  }
		}
					
	  }
	}
  }
}
Example #26
0
void* PoolThread::run(void *arg)
{
	PoolThread* ths = (PoolThread*)arg;
	ths->m_mutex->lock();
	bool console = ths->console;
	bool fl = ths->runFlag;
	ths->m_mutex->unlock();
	while (fl)
	{
		ths->mthread->wait();
		Task* task = ths->getTask();
		if (task)
		{
			try
			{
				if(!task->isFuture)
					task->run();
				else
				{
					FutureTask* ftask = static_cast<FutureTask*>(task);
					if(ftask!=NULL)
					{
						ftask->result = ftask->call();
						ftask->taskComplete();
					}
					else
					{
						task->run();
					}
				}
				if(task->cleanUp)
				{
					delete task;
				}
			}
			catch(exception& e)
			{
				if(console)
				{
					ths->logger << e.what() << flush;
				}
				if(task->isFuture)
				{
					FutureTask* ftask = static_cast<FutureTask*>(task);
					if(ftask!=NULL)
					{
						ftask->taskComplete();
					}
				}
			}
			catch(...)
			{
				if(console)
				{
					ths->logger << "Error Occurred while executing task" << flush;
				}
				if(task->isFuture)
				{
					FutureTask* ftask = static_cast<FutureTask*>(task);
					if(ftask!=NULL)
					{
						ftask->taskComplete();
					}
				}
			}
			ths->release();
		}
		ths->m_mutex->lock();
		fl = ths->runFlag;
		ths->m_mutex->unlock();
	}
	ths->m_mutex->lock();
	ths->complete = true;
	ths->m_mutex->unlock();
	return NULL;
}
void ThreadPool::processTasks(int procType, int tid)
{
	cv::gpu::Stream stream;

	// stream used to perform datat prefetching
	cv::gpu::Stream pStream;

	// Inform that this threads was created.
	//sem_post(&createdThreads);
	pthread_mutex_unlock(&createdThreads);

	printf("procType:%d  tid:%d waiting init of execution\n", procType, tid);
	pthread_mutex_lock(&initExecutionMutex);
	pthread_mutex_unlock(&initExecutionMutex);

	Task* curTask = NULL;
	Task* preAssigned = NULL;
	Task* prefetchTask = NULL;

	// ProcessTime example
	struct timeval startTime;
	struct timeval endTime;

	// Increment tasks semaphore to avoid the thread from get stuck when taking the prefeteched task
	if(this->prefetching ==  true){
		// Each GPU has one extra task available to compute.
		this->tasksQueue->releaseThreads(this->numGPUThreads);
	}

	while(true){

		curTask = this->tasksQueue->getTask(procType);
		if(curTask == NULL){

			if(this->execEngine->getCountTasksPending() != 0 || this->execDone == false){

				// Did not actually took a task, so increment the number of tasks processed
				this->tasksQueue->incrementTasksToProcess();

				// if, for any reason, could not return a new tasks a prefetchTask exist, compute the pre-fetched one
				if(prefetchTask != NULL){
					curTask = prefetchTask;
					prefetchTask = NULL;

					goto procPoint;
				}
				usleep(10000);

				// All tasks ready to execute are finished, but there still existing tasks pending due to unsolved dependencies
				continue;
			}


			printf("procType:%d  tid:%d Task NULL #t_pending=%d\n", procType, tid, this->execEngine->getCountTasksPending());
			break;
		}
		uploadPoint:


		procPoint:

		gettimeofday(&startTime, NULL);
		try{
			// if GPU, it is necessary to upload input data
			if(procType == ExecEngineConstants::GPU){

				enqueueUploadTaskParameters(curTask, stream);
				stream.waitForCompletion();
			}
			curTask->run(procType, tid);

			if(this->dataLocalityAware){
				if(procType ==  ExecEngineConstants::GPU){
					std::cout << "AFTER run: isDataLocalityAware!"<<std::endl;
					// 1) call pre-assignment.
					preAssigned = curTask->tryPreassignment();
					if(preAssigned != NULL){
						preassignmentSelectiveDownload(curTask, preAssigned, stream);

					}else{
						std::cout << "Preassignement NULL!!!"<<std::endl;
					}

				}
			}

			// there is not task preAssigned, so download everything until the next tasks is chosen for execution
			if(preAssigned == NULL){
				if(procType == ExecEngineConstants::GPU)
					downloadTaskOutputParameters(curTask, stream);
//				// If GPU, download output data residing in GPU
//				if(procType == ExecEngineConstants::GPU){
//					for(int i = 0; i < curTask->getNumberArguments(); i++){
//						// Donwload only those parameters that are of type: output, or
//						// input_output. Input type arguments can be deleted directly.
//						if(curTask->getArgument(i)->getType() != ExecEngineConstants::INPUT){
//							curTask->getArgument(i)->download(stream);
//						}
//					}
//					stream.waitForCompletion();
//					for(int i = 0; i < curTask->getNumberArguments(); i++){
//						curTask->getArgument(i)->deleteGPUData();
//					}
//				}
			}


		}catch(...){
			printf("ERROR in tasks execution. EXCEPTION");
		}

		gettimeofday(&endTime, NULL);

		// Resolve pending dependencies.

		// calculate time in microseconds
		double tS = startTime.tv_sec*1000000 + (startTime.tv_usec);
		double tE = endTime.tv_sec*1000000  + (endTime.tv_usec);
		printf("procType:%d  tid:%d Task speedup = %f procTime = %f\n", procType, tid, curTask->getSpeedup(), (tE-tS)/1000000);
		delete curTask;

		if(preAssigned != NULL){
			curTask = preAssigned;
			preAssigned = NULL;
			goto procPoint;
		}

	}

//	printf("Leaving procType:%d  tid:%d #t_pending=%d\n", procType, tid, this->execEngine->getCountTasksPending());
//	if(ExecEngineConstants::GPU == procType && gpuTempDataSize >0){
//		cudaFreeMemWrapper(gpuTempData[tid]);
//	}
	// I don't care about controlling concurrent access here. Whether two threads
	// enter this if, their resulting gettimeofday will be very similar if not the same.
	if(firstToFinish){
		firstToFinish = false;
		gettimeofday(&firstToFinishTime, NULL);
	}

	gettimeofday(&lastToFinishTime, NULL);
}