예제 #1
0
MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const ModePredicate& predicate, WaitMode waitMode)
{
    ASSERT(context);
    ASSERT(context->thread().threadID() == currentThread());

    double absoluteTime = 0.0;
    if (waitMode == WaitForMessage)
        absoluteTime = (predicate.isDefaultMode() && m_sharedTimer->isActive()) ? m_sharedTimer->fireTime() : MessageQueue<Task>::infiniteTime();
    MessageQueueWaitResult result;
    auto task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);

    // If the context is closing, don't execute any further JavaScript tasks (per section 4.1.1 of the Web Workers spec).  However, there may be implementation cleanup tasks in the queue, so keep running through it.

    switch (result) {
    case MessageQueueTerminated:
        break;

    case MessageQueueMessageReceived:
        task->performTask(*this, context);
        break;

    case MessageQueueTimeout:
        if (!context->isClosing())
            m_sharedTimer->fire();
        break;
    }

    return result;
}
예제 #2
0
void BuoysTask::moduleEnableCallback(const Robosub::ModuleEnableMsg& msg)
{
    if (msg.Module == "BuoysTask")
    {
        if (msg.State == true)
        {
            bool status = false;
            printf("BuoysTask: Enabled\n");
            m_isEnabled = true;

            // Perform task
            status = performTask();

            // Signal task complete on topic with task finish status
            std_msgs::String taskCompleteMsg;

            if (status)
            {
                taskCompleteMsg.data = "BuoysTask Success";
            }
            else
            {
                taskCompleteMsg.data = "BuoysTask Failure";
            }
            m_taskCompletePublisher.publish(taskCompleteMsg);
            m_isEnabled = false;
        }
        else
        {
            printf("BuoysTask: Disabled\n");
            m_isEnabled = false;
        }
    }
}
예제 #3
0
void SchemeMachine::launch(bool verbose){
	while(!tasks.isEmpty()){
		performTask();
		if(verbose){
			printf("\n\n\t\tCycle ## %d\n", cycle++);
			printf("\tTask stack::\n");
			tasks.print();
			printf("\tResult stack::\n");
			results.print();
			if(local_names != NULL){
				int level = 0;
				printf("\tLocal names::");
				for(local_names_t * curr = local_names; curr != NULL; curr = curr->prev){
					printf("\nlevel#%d ", level++);
					curr->current->print();
				}
				printf("\n");
			}
			if(global_names.size != 0){
				printf("\tGlobal names::");
				for(int i = 0; i < global_names.size; ++i){
					printf(" [%d ", global_names.ids[i]);
					(*global_names.refs[i])->print();
					printf("]\n");
//					printf(" [%d]", global_names.ids[i]);
				}
				printf("\n");
			}
		}
	}
}
예제 #4
0
void ItemThread::run()
{
    while (!isStopped())
    {
        doPause();

        if (!performTask())
            m_WaitCond.wait(2);
    }
}
/*This function is called on each interrupt. It reads the buffer, sets
the time for the next interrupt, and executes the action given in the
previous entry.*/
void StepperControl::interruptExec(){
	interruptCounter++; //Counting the interrupts. Currently serves no practical purpose (was used by older versions of this library).
	
	uint8_t exec = (uint8_t)(executionIndex%bufferSize); //Proper execution index based on buffer size.
	int bCheck = bufferCheck(1); //Buffer state.
	
	//As long as there is no waiting time given for the current task, but the buffer isn't empty, go to next task.
	while(taskList[1][exec] == 0 && bCheck){
		bCheck = bufferCheck(1);
		if(bCheck){
			++executionIndex;
		}else{
			--executionIndex;
		}
		exec = (uint8_t)(executionIndex%bufferSize);
	}
	
	//Adjusting values for new executionIndex.
	uint8_t exec1 = (uint8_t)(executionIndex-1);
	exec1 = exec1%bufferSize; //%bufferSize would be ignored it was added to the previous line. No idea, why.

	//If there are entries in the buffer, execute task from previous line (if there is anything to be done).
	if(bCheck){
		performTask(exec1);
	}
	
	//If the buffer underrun check failed, wait some time before trying again.
	if(!bCheck){
		++idleCounter; //Increase idle counter. This will be used in future versions to subtract the idle time from the next step, allowing more consistent movement.
		OCR1A = idleTime;
		return;
	}
	
	//If the time entries aren't empty, set new waiting time.
	//If the next task is further away than the timer would be able to count, wait for overflow and reduce overflow counter by 1.
	if(taskList[1][exec] > 2){
		--taskList[1][exec];
		OCR1A = 65535;
	}
	//If the next task is exactly as far as the timer would be able to count, set timer to max. value and move on to next entry.
	else if(taskList[1][exec] == 2 && taskList[0] == 0){
		taskList[1][exec] = taskList[1][exec]-2;
		OCR1A = 65535;
		++executionIndex;
	}
	//If the next task is due in less than the overflow time, set the timer to that time and move up to next entry.
	else if(taskList[1][exec] == 1 && taskList[0] > 0){
		OCR1A = taskList[0][exec];
		taskList[0][exec] = 0;
		--taskList[1][exec];
		++executionIndex;
	}
}
예제 #6
0
void StoreDataVessel::recompute( const unsigned& ivec, const unsigned& jstore ){
  plumed_dbg_assert( getAction()->derivativesAreRequired() && getAction()->lowmem && jstore<max_lowmem_stash );
  // Set the task we want to reperform
  setTaskToRecompute( ivec );
  // Reperform the task
  performTask( jstore );
  // Store the derivatives
  storeDerivativesLowMem( jstore );
 
  // Clear up afterwards
  getAction()->clearAfterTask();
}
예제 #7
0
void WorkerRunLoop::runCleanupTasks(WorkerGlobalScope* context)
{
    ASSERT(context);
    ASSERT(context->thread().threadID() == currentThread());
    ASSERT(m_messageQueue.killed());

    while (true) {
        auto task = m_messageQueue.tryGetMessageIgnoringKilled();
        if (!task)
            return;
        task->performTask(*this, context);
    }
}
예제 #8
0
MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const ModePredicate& predicate, WaitMode waitMode)
{
    ASSERT(context);
    ASSERT(context->thread().threadID() == currentThread());

#if PLATFORM(GTK) || PLATFORM(WPE)
    GMainContext* mainContext = g_main_context_get_thread_default();
    if (g_main_context_pending(mainContext))
        g_main_context_iteration(mainContext, FALSE);
#endif

    double deadline = MessageQueue<Task>::infiniteTime();

#if USE(CF)
    CFAbsoluteTime nextCFRunLoopTimerFireDate = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    double timeUntilNextCFRunLoopTimerInSeconds = nextCFRunLoopTimerFireDate - CFAbsoluteTimeGetCurrent();
    deadline = currentTime() + std::max(0.0, timeUntilNextCFRunLoopTimerInSeconds);
#endif

    double absoluteTime = 0.0;
    if (waitMode == WaitForMessage) {
        if (predicate.isDefaultMode() && m_sharedTimer->isActive())
            absoluteTime = std::min(deadline, m_sharedTimer->fireTime());
        else
            absoluteTime = deadline;
    }
    MessageQueueWaitResult result;
    auto task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);

    // If the context is closing, don't execute any further JavaScript tasks (per section 4.1.1 of the Web Workers spec).  However, there may be implementation cleanup tasks in the queue, so keep running through it.

    switch (result) {
    case MessageQueueTerminated:
        break;

    case MessageQueueMessageReceived:
        task->performTask(*this, context);
        break;

    case MessageQueueTimeout:
        if (!context->isClosing())
            m_sharedTimer->fire();
#if USE(CF)
        if (nextCFRunLoopTimerFireDate <= CFAbsoluteTimeGetCurrent())
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, /*returnAfterSourceHandled*/ false);
#endif
        break;
    }

    return result;
}
예제 #9
0
void ThreadableBlobRegistry::registerBlobURLOptionallyFileBacked(const URL& url, const URL& srcURL, const String& fileBackedPath)
{
    if (isMainThread())
        blobRegistry().registerBlobURLOptionallyFileBacked(url, srcURL, BlobDataFileReference::create(fileBackedPath));
    else {
        threadableQueue().append(createCrossThreadTask(ThreadableBlobRegistry::registerBlobURLOptionallyFileBacked, url, srcURL, fileBackedPath));

        callOnMainThread([] {
            auto task = threadableQueue().tryGetMessage();
            ASSERT(task);
            task->performTask();
        });
    }
}
예제 #10
0
void TorpedoTask::moduleEnableCallback(const Robosub::ModuleEnableMsg& msg)
{
    if (msg.Module == "TorpedoTask")
    {
        if (msg.State == true)
        {
            bool status = false;
            printf("TorpedoTask: Enabled\n");
            m_isEnabled = true;

            status = performTask();

            // @todo Signal task complete on topic with task finish status
        }
        else
        {
            printf("TorpedoTask: Disabled\n");
            m_isEnabled = false;
        }
    }
}
예제 #11
0
void ActionWithVessel::runAllTasks(){
  if( getExchangeStep() && nactive_tasks!=fullTaskList.size()  ) error("contributors must be unlocked during exchange steps");
  plumed_massert( functions.size()>0, "you must have a call to readVesselKeywords somewhere" );
  unsigned stride=comm.Get_size();
  unsigned rank=comm.Get_rank();
  if(serial){ stride=1; rank=0; }

  // Make sure jobs are done
  doJobsRequiredBeforeTaskList();

  for(unsigned i=rank;i<nactive_tasks;i+=stride){
      // The index of the task in the full list
      task_index=indexOfTaskInFullList[i];
      // Store the task we are currently working on
      current=partialTaskList[i];
      // Calculate the stuff in the loop for this action
      performTask();
      // Weight should be between zero and one
      plumed_dbg_assert( thisval[1]>=0 && thisval[1]<=1.0 );

      // Check for conditions that allow us to just to skip the calculation
      // the condition is that the weight of the contribution is low 
      // N.B. Here weights are assumed to be between zero and one
      if( thisval[1]<tolerance ){
         // Clear the derivatives
         clearAfterTask();  
         // Deactivate task if it is less than the neighbor list tolerance
         if( thisval[1]<nl_tolerance && contributorsAreUnlocked ) deactivate_task();
         continue;
      }

      // Now calculate all the functions
      // If the contribution of this quantity is very small at neighbour list time ignore it
      // untill next neighbour list time
      if( !calculateAllVessels() && contributorsAreUnlocked ) deactivate_task();
  }
  finishComputations();
}
예제 #12
0
int main(int argc, char* argv[])
{
	try
	{
		if(argc<2)
		{
			printAndWait("Usage: csDosBridge <inputFilePath>");
			return(1);
		}

		LPCTSTR lpszInPath = argv[1];
		if(-1 == _access(lpszInPath, 0))
		{
			cerr << "The file " << lpszInPath << " was not found.\n";
			printAndWait("");
			return(1);
		}

		//HKEY k;
		//::OpenRegKey(HKCU, "Software\\VB and VBA Program Settings\csBridge\Settings");

		char lpszSettings[MAX_PATH];
		strcpy(lpszSettings, lpszInPath);
		strcat(lpszSettings, ".csb");

		if(-1 == _access(lpszSettings, 0)) // if settings for this file are not found
		{
			runVBBridge(argv[0], lpszInPath);
			return(0);
		}

		// we have the task file
		HRESULT hr;
		hr = ::CoInitialize(NULL);
		if(FAILED(hr))
		{
			printAndWait("Couldn't initialize COM. How can that be?\n");
			return 1;
		}

		ITaskPtr qTask;
		hr = qTask.CreateInstance(CLSID_TaskImpl);
		if(FAILED(hr))
		{
			printAndWait("Couldn't create a TaskImpl.  Try reinstalling CarlaStudio.\n");
			return 1;
		}

		IPersistStreamInitPtr qPersist(qTask);
		// we don't need to check return values because this smart ptr will throw exceptions

		hr = qPersist->InitNew();
		assert(!FAILED(hr));

		_bstr_t bstrSettingsPath(lpszSettings);
		hr = qTask->Load(bstrSettingsPath);
		if(FAILED(hr))
		{
			printAndWait("Couldn't load settings file. Running csBridge\n");
			runVBBridge(argv[0], lpszInPath);
			return 0;
		}

		performTask(qTask);
	}
	catch(_com_error e)
	{
		cerr << e.Description() << "\n";
	}
	return 0;
}
예제 #13
0
QVector<QVariant> MasterSlaveCommunicator::performTask(QVector<QVariant> inputVector)
{
    return performTask(0, inputVector);
}
예제 #14
0
void ActionWithVessel::runAllTasks(){
  if( getExchangeStep() && nactive_tasks!=fullTaskList.size()  ) error("contributors must be unlocked during exchange steps");
  plumed_massert( functions.size()>0, "you must have a call to readVesselKeywords somewhere" );
  unsigned stride=comm.Get_size();
  unsigned rank=comm.Get_rank();
  if(serial){ stride=1; rank=0; }

  // Make sure jobs are done
  if(timers) stopwatch.start("1 Prepare Tasks");
  doJobsRequiredBeforeTaskList();
  if(timers) stopwatch.stop("1 Prepare Tasks");

  // Get number of threads for OpenMP
  unsigned nt=OpenMP::getNumThreads();
  if( nt*stride*10>nactive_tasks) nt=nactive_tasks/stride/10;
  if( nt==0 ) nt=1;

  // Get size for buffer
  unsigned bsize=0, bufsize=getSizeOfBuffer( bsize ); 
  // Clear buffer
  buffer.assign( buffer.size(), 0.0 );
  // Switch off calculation of derivatives in main loop
  if( dertime_can_be_off ) dertime=false;

  // std::vector<unsigned> der_list;
  // if( mydata ) der_list.resize( mydata->getSizeOfDerivativeList(), 0 ); 

  // Build storage stuff for loop
  // std::vector<double> buffer( bufsize, 0.0 );

  if(timers) stopwatch.start("2 Loop over tasks");
#pragma omp parallel num_threads(nt)
{
  std::vector<double> omp_buffer;
  if( nt>1 ) omp_buffer.resize( bufsize, 0.0 );
  MultiValue myvals( getNumberOfQuantities(), getNumberOfDerivatives() );
  MultiValue bvals( getNumberOfQuantities(), getNumberOfDerivatives() );
  myvals.clearAll(); bvals.clearAll();
 
#pragma omp for nowait
  for(unsigned i=rank;i<nactive_tasks;i+=stride){
      // Calculate the stuff in the loop for this action
      performTask( indexOfTaskInFullList[i], partialTaskList[i], myvals );
      // Weight should be between zero and one
      plumed_dbg_assert( myvals.get(0)>=0 && myvals.get(0)<=1.0 );

      // Check for conditions that allow us to just to skip the calculation
      // the condition is that the weight of the contribution is low 
      // N.B. Here weights are assumed to be between zero and one
      if( myvals.get(0)<tolerance ){
         // Deactivate task if it is less than the neighbor list tolerance
         if( myvals.get(0)<nl_tolerance && contributorsAreUnlocked ) deactivate_task( indexOfTaskInFullList[i] );
         // Clear the derivatives
         myvals.clearAll();
         continue;
      }

      // Now calculate all the functions
      // If the contribution of this quantity is very small at neighbour list time ignore it
      // untill next neighbour list time
      if( nt>1 ){
          if( !calculateAllVessels( indexOfTaskInFullList[i], myvals, bvals, omp_buffer, der_list ) && contributorsAreUnlocked ) deactivate_task( indexOfTaskInFullList[i] );
      } else {
          if( !calculateAllVessels( indexOfTaskInFullList[i], myvals, bvals, buffer, der_list ) && contributorsAreUnlocked ) deactivate_task( indexOfTaskInFullList[i] );
      }

      // Clear the value
      myvals.clearAll();
  }
#pragma omp critical
  if(nt>1) for(unsigned i=0;i<bufsize;++i) buffer[i]+=omp_buffer[i];
}
  if(timers) stopwatch.stop("2 Loop over tasks");
  // Turn back on derivative calculation
  dertime=true;

  if(timers) stopwatch.start("3 MPI gather");
  // MPI Gather everything
  if( !serial && buffer.size()>0 ) comm.Sum( buffer );
  // MPI Gather index stores
  if( mydata && !lowmem && !noderiv ){ 
     comm.Sum( der_list ); mydata->setActiveValsAndDerivatives( der_list ); 
  }
  // Update the elements that are makign contributions to the sum here
  // this causes problems if we do it in prepare
  if( !serial && contributorsAreUnlocked ) comm.Sum( taskFlags );
  if(timers) stopwatch.stop("3 MPI gather");

  if(timers) stopwatch.start("4 Finishing computations");
  finishComputations( buffer );
  if(timers) stopwatch.stop("4 Finishing computations");
}
예제 #15
0
void CApplication::runMainLoop()
{
   while (true)
   {
      SDL_PumpEvents();

      /*** PROCESS KEYSTATE ***/

      int numkeys;
      unsigned char* keystate = SDL_GetKeyState(&numkeys);

      if (keystate[SDLK_ESCAPE])
      {
         break;
      }

      /*** WINDOWS EVENTS ***/
      bool isQuit = false;
      SDL_Event sdlEvent; 

      /*** PROCESS EVENTS ***/ 
    
   while (SDL_PollEvent(&sdlEvent))
      {
         switch (sdlEvent.type)
         {
		  		
		 case SDL_MOUSEBUTTONDOWN:		
			 if (sdlEvent.button.button == SDL_BUTTON_LEFT)	 {
				 int x = sdlEvent.button.x;
				 int y = sdlEvent.button.y;
				 if ((x > 10) && (x < 100) && (y > 10) && (y < 100))				
				 ShellExecute(NULL, "open", "help.html", NULL, NULL, SW_SHOWNORMAL);
			 }
			 
			 break;

         case SDL_QUIT:
            isQuit = true;
            break;
         case SDL_VIDEORESIZE: 
			 mRenderer->resize(sdlEvent.resize.w, sdlEvent.resize.h); break;
         case SDL_KEYDOWN:
            switch (sdlEvent.key.keysym.sym)
            {
            //case SDLK_q:     mRenderer->resize(640, 480);  break;
            case SDLK_EQUALS:
            case SDLK_KP8:   mRenderer->scaleModel(glm::vec3(1.2f)); break;
			 
            case SDLK_MINUS:
            case SDLK_KP2:   mRenderer->scaleModel(glm::vec3(0.8f)); break;

			case SDLK_9:
            case SDLK_KP9:   mRenderer->rotateModel(glm::vec3( 15,   0,   0)); break;
			case SDLK_7:
            case SDLK_KP7:   mRenderer->rotateModel(glm::vec3(-15,   0,   0)); break;
			case SDLK_6:
            case SDLK_KP6:   mRenderer->rotateModel(glm::vec3(  0,  15,   0)); break;
			case SDLK_4:
            case SDLK_KP4:   mRenderer->rotateModel(glm::vec3(  0, -15,   0)); break;
			case SDLK_3:
            case SDLK_KP3:   mRenderer->rotateModel(glm::vec3(  0,   0,  15)); break;
			case SDLK_1:
            case SDLK_KP1:   mRenderer->rotateModel(glm::vec3(  0,   0, -15)); break;

			case SDLK_5:
			case SDLK_KP5:   mRenderer->resetTransform(); break;

            case SDLK_RIGHT: mRenderer->translateModel(glm::vec3( 2, 0,   0)); break;
            case SDLK_LEFT:  mRenderer->translateModel(glm::vec3(-2, 0,   0)); break;
            case SDLK_UP:    mRenderer->translateModel(glm::vec3(  0, 0, -2)); break;
            case SDLK_DOWN:  mRenderer->translateModel(glm::vec3(  0, 0,  2)); break;
           
			case SDLK_SPACE: mRenderer->screenshot(); break;
				 

				
				 break;

			default:
               break;
            }
            break;
         default:
            break;
         }
      }

      if (isQuit)
      {
         break;
      }

      /*** PERFORM TASK ***/
      bool result = performTask();
      if (false == result)
      {
         break;
      }

      SDL_GL_SwapBuffers();
      SDL_Delay(10);
   }
}