示例#1
0
/*BEGIN LocateGate*/
NewDriveMode LocateGate::step(NewAutoPilot&newAutoPilot, double dt)
{
	auto &gateInSight = newAutoPilot.gateInSight;
	auto &coilgun = newAutoPilot.coilgun;
	auto &ballInTribbler = newAutoPilot.ballInTribbler;
	auto &wheels = newAutoPilot.wheels;
	auto &sightObstructed = newAutoPilot.sightObstructed;
	auto &lastGateLocation = newAutoPilot.lastGateLocation;

	boost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();

	if (!ballInTribbler) return DRIVEMODE_LOCATE_BALL;
	if (gateInSight) {
		std::chrono::milliseconds dura(100); // do we need to sleep?
		std::this_thread::sleep_for(dura);
		wheels->Stop();
		return DRIVEMODE_AIM_GATE;
	}
	//wheels->Rotate(0, 50);
	
	//int s = sign((int)lastGateLocation.horizontalAngle);

	wheels->Rotate(lastGateLocation.horizontalAngle < 0, 30);
	
	return DRIVEMODE_LOCATE_GATE;
}
示例#2
0
void CSystem::Sleep(long long milliseconds)
{
#if (_MSC_VER >= 1800)
	std::chrono::milliseconds dura(milliseconds);
	std::this_thread::sleep_for(dura);
#endif
}
示例#3
0
文件: main.cpp 项目: CCJY/coliru
int main()
{
    std::cout << "Hello waiter" << std::endl;
    std::chrono::milliseconds dura( 2000 );
    std::this_thread::sleep_for( dura );
    std::cout << "Waited 2000 ms\n";
}
void CorosyncCpg::shutdown() {
  if (!ready) {
    return;
  }
  ready = false;
  LOG(INFO)<< "shutdown corosync.";
  if (handle) {
    cs_error_t result;
    unsigned int snooze = 10;
    for (unsigned int nth_try = 0; nth_try < cpgRetries; ++nth_try) {
      if (CS_OK == (result = cpg_finalize(handle))) {
        break;
      } else if (result == CS_ERR_TRY_AGAIN) {
        LOG(WARNING)<< "Retrying finalize";
        std::chrono::microseconds dura(snooze);
        std::this_thread::sleep_for(dura);
        snooze *= 10;
        snooze = (snooze <= maxCpgRetrySleep) ? snooze : maxCpgRetrySleep;
      }
      else break;  // Don't retry unless CPG tells us to.
    }

    if (result != CS_OK) {
      LOG(ERROR)<< "cpg_finalize error, error code = " << result;
    }
  }
  handle = 0;
}
cs_error_t CorosyncCpg::init() {
  if (ready) {
    return CS_OK;
  }
  cpg_callbacks_t callbacks;
  ::memset(&callbacks, 0, sizeof(callbacks));
  callbacks.cpg_deliver_fn = &globalDeliver;
  callbacks.cpg_confchg_fn = &globalConfigChange;

  //    QPID_LOG(notice, "Initializing CPG");
  cs_error_t err = cpg_initialize(&handle, &callbacks);
  int retries = 6; // @todo: make this configurable.
  while (err == CS_ERR_TRY_AGAIN && --retries) {
    LOG(WARNING)<< "cpg initialize retry " << retries;
    std::chrono::microseconds dura(5);
    std::this_thread::sleep_for(dura);
    err = cpg_initialize(&handle, &callbacks);
  }
  if (err != CS_OK) {
    LOG(ERROR)<< "cpg_initialize error, caused by " << error2str(err);
    return err;
  }
  if (CS_OK != cpg_context_set(handle, this)) {
    LOG(ERROR)<< "Cannot set CPG context";
    return err;
  }

  ready = true;
  return CS_OK;
}
示例#6
0
文件: tsp.cpp 项目: danwa223/TDDD86
int main(int argc, char *argv[]) {

    QApplication a(argc, argv);

	// define 4 points forming a square
	Point p(100.0, 100.0);
	Point q(500.0, 100.0);
	Point r(500.0, 500.0);
	Point s(100.0, 500.0);
	// Set up a Tour with those four points
	// The constructor should link p->q->r->s->p
	Tour squareTour(p, q, r, s);
	squareTour.show();

    string filename = "tsp10.txt";
    ifstream input;
    input.open(filename);

    // get dimensions
    int width;
    int height;
    input >> width;
    input >> height;

    // setup graphical window
    QGraphicsView *view = new QGraphicsView();
    QGraphicsScene *scene = new QGraphicsScene();
    view->setScene(scene);
    view->scale(1, -1); //screen y-axis is inverted
    view->setSceneRect(0, 0, width, height);
    view->show();

    // run insertion heuristic
    Tour tour;
    double x;
    double y;
    while (input >> x >> y) {
        Point p(x, y);
		//tour.insertNearest(p);
        tour.insertSmallest(p);
        //uncomment the 4 lines below to animate
		tour.draw(scene);
		std::chrono::milliseconds dura(50);
		std::this_thread::sleep_for(dura);
		a.processEvents();
	}
    input.close();

    // print tour to standard output
    cout << "Tour distance: " << std::fixed << std::setprecision(4)
         << std::showpoint << tour.distance() << endl;
    cout << "Number of points: " << tour.size() << endl;
	tour.show();

    // draw tour
    tour.draw(scene);
	return a.exec(); // start Qt event loop
}
示例#7
0
/*BEGIN DriveToHome*/
NewDriveMode DriveToHome::step(NewAutoPilot&newAutoPilot, double dt)
{
	newAutoPilot.wheels->Forward(-40);
	std::chrono::milliseconds dura(300);
	std::this_thread::sleep_for(dura);
	newAutoPilot.wheels->Forward(0);

	return DRIVEMODE_LOCATE_BALL;
}
示例#8
0
void Thread::sleep_s (ssi_time_t seconds) {
    #if hasCXX11threads

    std::chrono::milliseconds dura((int)(seconds*1000 +0.5));
    std::this_thread::sleep_for( dura );
    #else
	::Sleep (ssi_cast (DWORD, 1000.0*seconds + 0.5));
    #endif // hasCXX11threads
}
		static void ThreadedStartTask(Dia::Application::Module* pModule)
		{
			std::chrono::milliseconds dura(2000);
			std::this_thread::sleep_for(dura);

			// Ok this is not thread safe but that not the point, it would be the system that 
			//	lives in here that should manage its threading.
			pModule->NotifyReadyToStartAsync();
		}
示例#10
0
void LoginServer::Run()
{
	while (true)
	{

		std::chrono::milliseconds dura(40);
		std::this_thread::sleep_for(dura);
	}
}
示例#11
0
void Thread::sleep_ms (ssi_size_t milliseconds) {

    #if hasCXX11threads
    std::chrono::milliseconds dura(milliseconds);
    std::this_thread::sleep_for( dura  );
    #else
    ::Sleep (milliseconds);
    #endif // hasCXX11threads

}
示例#12
0
void
simple_schedule::start()
{
   auto &container( kernel_set.acquire() );
   for( auto * const k : container )
   {  
      auto * const th_info( new thread_info_t( k ) );
#ifdef CORE_ASSIGN
      th_info->loc = (*core_assign)[ reinterpret_cast< std::uintptr_t >( k ) ];
#endif
      thread_map.emplace_back( th_info );
   }
   kernel_set.release();

   bool keep_going( true );
   while( keep_going )
   {
      while( not thread_map_mutex.try_lock() )
      {
         std::this_thread::yield();
      }     
      //exit, we have a lock
      keep_going = false;
      for( auto  *t_info : thread_map )
      {
         if( ! t_info->term )
         {
            if( t_info->finished )
            {
               /**
                * FIXME: the list could get huge for long running apps,
                * need to delete these entries...especially since we have
                * a lock on the list now 
                */
               t_info->th.join();
               t_info->term = true;
            }
            else /* ! finished */
            {
               keep_going =  true;
            }
         }
      }
      //if we're here we have a lock and need to unlock
      thread_map_mutex.unlock();
      /**
       * NOTE: added to keep from having to unlock these so frequently
       * might need to make the interval adjustable dep. on app
       */
      std::chrono::milliseconds dura( 3 );
      std::this_thread::sleep_for( dura );
   }
   return;
}
示例#13
0
文件: main.cpp 项目: txjohnson/mlfifo
void read_items (int no) {
	std::cout << "Entering thead " << no << std::endl;
	int x;
	while (true) {
		while (!f.get(x));
		std::cout << "thread " << no << ": item " << x << std::endl;
		if (x == 1000) return;
		std::chrono::milliseconds dura( std::rand() % 2000 );
		std::this_thread::sleep_for( dura );
	}
}
示例#14
0
/*BEGIN DriveToBall*/
void DriveToBall::onEnter(NewAutoPilot&newAutoPilot)
{
	DriveInstruction::onEnter(newAutoPilot);
	newAutoPilot.lastBallCount = newAutoPilot.ballCount;
	newAutoPilot.wheels->Stop();
	std::chrono::milliseconds dura(200);
	std::this_thread::sleep_for(dura);
	newAutoPilot.coilgun->ToggleTribbler(false);
	start = newAutoPilot.lastBallLocation;
	//Desired distance
	target = { 350, 0, 0 };
}
示例#15
0
void TradingAdapter::closeSocket( int delayMillis) {
	if (this->socket != NULL) {
		// should we wait?
		if (delayMillis > 0) {
			std::chrono::milliseconds dura(delayMillis);
			std::this_thread::sleep_for(dura);
		}
		this->socket->disconnect();
		delete this->socket;
		this->socket = NULL;
	}
}
示例#16
0
文件: NDP.cpp 项目: erhodes/4203-Mesh
// Update
void NDP::update(){
  // update loop
  while(running){
    // Removal list
    vector<string> removals;
    // Lock
    barrier.lock();
    // Update neighbor table
    for(auto &n: neighbors){
      // Arrived
      if(n.getArrived() == true){
        // New neighbor
        if(n.getAge() == -1){
          // Notify IARP
		barrier.unlock();
          instance->foundNeighbor(n.getAddress());
		barrier.lock();
        }
        n.setAge(0);
        n.setArrived(false);
      }
      // Not arrived
      else{
        // Neighbor lost
        if(n.getAge() >= maxAge){
          // Add to removal list          
          removals.push_back(n.getAddress());
        }
        // Neighbor not lost yet
        else{
          // Increment age
          n.setAge(n.getAge() + 1);
        }
      }    
    }
    // Remove entries
    for(auto &a: removals){
      // Remove neighbor
      removeNeighbor(a);
      // Notify IARP      
	barrier.unlock();
      instance->lostNeighbor(a);
	barrier.lock();
    }
    // Unlock
    barrier.unlock();
    // SLeep for random duration
    chrono::milliseconds dura(
    rand() % (updateMaxDelay - updateMinDelay) + updateMinDelay);
    this_thread::sleep_for(dura);
  }
}
示例#17
0
 void run(Worker &wk)
 {
     int num = 0;
     while (!g_exit)
     {
         boost::chrono::milliseconds dura(2000);
         //boost::this_thread::sleep_for(dura);
         std::clog << "sender running " << std::endl;
         //wk.say();  ///可能是非线程安全的
         wk.io->post(boost::bind(&Worker::say, &wk)); ///线程安全
         wk.io->dispatch(boost::bind(&Worker::tellmetimes, &wk, num)); ///注意是&wk,是引用,否则bind会复制一个wk实例
         ++num;
     }
 }
示例#18
0
文件: NDP.cpp 项目: erhodes/4203-Mesh
// Beacon
void NDP::beacon(){
  // beacon loop
  while(running){
    // transmit beacon
    	time_t seconds;
    seconds = time(NULL);
    //cout << "SENDING OUT A BEACON "  << "\n";
    	wlan.send("ff:ff:ff:ff:ff:ff", "<BEACON>");
    	// Sleep
    	chrono::milliseconds dura(beaconDelay);
    	this_thread::sleep_for(dura);
  }
  return;
}
示例#19
0
bool test() {
  // define inputs and output
  const int vecSize = 8;
  const int loopCount = 1024 * 1024;
  const int cpuSleepMsec = 50;

  std::atomic_int table_a[vecSize];
  auto ptr_a = &table_a[0];

  std::atomic_bool done(false);
  auto ptr_done = &done;

  // initialize test data
  for (int i = 0; i < vecSize; ++i) {
    table_a[i].store(0);
  }

  // fire CPU thread
  std::thread cpu_thread([=]() {
    std::cout << "Enter CPU monitor thread..." << std::endl;
    std::chrono::milliseconds dura( cpuSleepMsec );
    while (!*ptr_done) {
      for (int i = 0; i < vecSize; ++i) {
        std::cout << std::setw(8) << (ptr_a + i)->load(std::memory_order_acquire);
        if (i < vecSize - 1) {
          std::cout << ", ";
        } else {
          std::cout << std::endl;
        }
      }

      std::this_thread::sleep_for( dura );
    }
    std::cout << "Leave CPU monitor thread." << std::endl;
  });

  // launch kernel
  Concurrency::extent<1> e(vecSize);
  parallel_for_each(
    e,
    [=](Concurrency::index<1> idx) restrict(amp) {

    int tid = idx[0];
    int counter = 0;

    while (++counter <= loopCount) {
      (ptr_a + tid)->fetch_add(1, std::memory_order_release);
    }
  });
    int operator()() {
        ++ cur_thd_count;

        value_ptr_type this_co = dynamic_cast<value_ptr_type>(copp::this_coroutine::get_coroutine());
        CASE_EXPECT_EQ(addr_, this_co);
        run_ = true;

        std::chrono::milliseconds dura( 4 );
        std::this_thread::sleep_for( dura );

        max_thd_count = std::max(max_thd_count, cur_thd_count.load());

        -- cur_thd_count;
        return 0;
    }
示例#21
0
int main(int argc, char** argv)
{
	std::vector<ALshort> samples;
	AL_Capture alc(MyAL::choisir_device(),MyAL::choisir_capture_device());
	alc.start(samples);
	std::chrono::milliseconds dura(1000);
	std::this_thread::sleep_for(dura);
	alc.stop();
	if(argc<2)
		alc.save_sound("test.wav");
	else
		alc.save_sound(argv[1]);
	return EXIT_SUCCESS;

}
示例#22
0
void Simulator::mainLoop (void) {
    // TODO: change duration so it limits to 100 updates a second, but allows
    // for slower times if the client really has to think about things.
    std::cout << "Mainloop running" << std::endl;
    while (running) {
        sendSensors();
        nextControl = getControl();
        entities->rocket->applyControl(nextControl);
        stepSimulation(1./100);

        // Rate limit the simulation
        std::chrono::milliseconds dura(10);
        std::this_thread::sleep_for(dura);
    }
    std::cout << "Mainloop not running" << std::endl;
}
示例#23
0
/*BEGIN RecoverCrash*/
NewDriveMode RecoverCrash::step(NewAutoPilot&newAutoPilot, double dt)
{
	double velocity2 = 0, direction2 = 0, rotate2 = 0;
	auto targetSpeed = newAutoPilot.wheels->GetTargetSpeed();

	//Backwards
	newAutoPilot.wheels->Drive(50, 180 - targetSpeed.heading);
	std::chrono::milliseconds dura(1000);
	std::this_thread::sleep_for(dura);
	newAutoPilot.wheels->Rotate(1, 50);
	std::this_thread::sleep_for(dura);
	
	newAutoPilot.wheels->Stop();

	return DRIVEMODE_LOCATE_BALL;
}
void MultiversoSkipGramMixture::PushDataBlock(
    std::queue<DataBlock*> &datablock_queue, DataBlock* data_block)
{

    multiverso::Multiverso::PushDataBlock(data_block);

    datablock_queue.push(data_block);
    //limit the max size of total datablocks to avoid out of memory
    while (static_cast<int64_t>(datablock_queue.size()) > m_option->max_preload_blocks_cnt)
    {
        std::chrono::milliseconds dura(200);
        std::this_thread::sleep_for(dura);

        RemoveDoneDataBlock(datablock_queue);
    }
}
示例#25
0
文件: main.cpp 项目: CCJY/coliru
int main()
{
    std::cout << "main thread id: " << std::this_thread::get_id() << std::endl;

    ActiveObject obj;
    std::chrono::milliseconds dura(200);
    std::this_thread::sleep_for(dura);

    for(int i=0; i < SIZE; ++i)
    {
        obj.doSomething(); // call is nonblocking
    }

    std::this_thread::sleep_for(std::chrono::seconds(2));

    std::cout <<  "main thread exited " << std::endl;
}
cs_error_t CorosyncCpg::leave() {
  cs_error_t result;
  unsigned int snooze = 10;
  for (unsigned int nth_try = 0; nth_try < cpgRetries; ++nth_try) {
    if (CS_OK == (result = cpg_leave(handle, &group))) {
      break;
    } else if (result == CS_ERR_TRY_AGAIN) {
      LOG(WARNING)<< "Retrying leave";
      std::chrono::microseconds dura(snooze);
      std::this_thread::sleep_for(dura);
      snooze *= 10;
      snooze = (snooze <= maxCpgRetrySleep) ? snooze : maxCpgRetrySleep;
    }
    else break;  // Don't retry unless CPG tells us to.
  }
  return result;

}
示例#27
0
av::NetNodeServer::NetNodeServer(const std::string& host, const std::string& port, av::NetNode* netnode, const std::string& ce, const std::string& se, uint64_t hwm)
  : mHost(host),
    mPort(port),
    mNetNode(netnode),
    mCtx(1),
    mSocket(mCtx, ZMQ_PUB),
    mClientEndpoint(ce),
    mServerEndpoint(se)
{
  //int64_t  rate(500);
  //mSocket.setsockopt(ZMQ_RATE,&rate, sizeof(rate));

  mSocket.setsockopt(ZMQ_HWM,&hwm, sizeof(hwm));
  std::string endpoint("tcp://" + mHost + ":" + mPort);
  mSocket.bind(endpoint.c_str());
  std::chrono::milliseconds dura(200);
  std::this_thread::sleep_for(dura);
}
示例#28
0
void ArduinoBoard::Run2(){
	std::string resp;
	std::chrono::milliseconds dura(60);
	std::vector<std::string> items;
	std::vector<std::string> item;
	while (!stop_thread){
		
		//writeString("info\n");
		//std::this_thread::sleep_for(dura);
		//resp = readLineAsync(60).c_str();
		resp = readLine().c_str();
		//std::cout << "Arduino, resp='"<< resp <<"'"<<std::endl;
 		//"<start:"+strt+">"+"<gate:"+gate+">"+"<s1:"+distance0+">"+"<s2:"+distance1+">"+"<s3:"+distance2+">"
		resp = ">" + resp;
		boost::split(items, resp, boost::is_any_of(">"));
		for(auto i : items) {
			if(i.empty()) continue;
			boost::split(item, i, boost::is_any_of(":"));
			if (item.size()==2) {
				if(item[0] == "<start") {
					int res = atoi(item[1].c_str());
					// set start off if change from arduino 1 -> 0
					if (res == 0 && old_start == 1) {
						old_start = 0;
					} else if(res == 1) {
						start = 1; 
						old_start = 1;
					} else /* 0 && 0*/ {
						old_start = 0;
					}
				}
				if(item[0] == "<gate") gte = atoi(item[1].c_str());
				if(item[0] == "<s1") sonars.x = atoi(item[1].c_str());
				if(item[0] == "<s2") sonars.y = atoi(item[1].c_str());
				if(item[0] == "<s3") sonars.z = atoi(item[1].c_str());
			} else {
				//std::cout << "Arduino, invalid responce item: '" << i << "', " << ", res2p: '" << resp << "'" << std::endl; 
			}
		}
		
		//std::this_thread::sleep_for(dura);
		
	}
}
示例#29
0
int StoreClient::Send()
{
  //Send fileName
  send(BaseClient::mSocket, mFilename.c_str(), mFilename.size(), 0);
  
  //Small delay
  std::chrono::milliseconds dura( 500 );
  std::this_thread::sleep_for( dura );
  
  //send bytesInFile
  mBytesInFile = htonl(mBytesInFile);
  send(BaseClient::mSocket, &mBytesInFile, sizeof(mBytesInFile), 0);
  
  //Small delay
  std::this_thread::sleep_for( dura );
  
  //send fileBuffer
  send(BaseClient::mSocket, mFileBuffer, MAX, 0);
}
示例#30
0
void HostHealthMonitor::monitor() {
  // wait hhvm finish bootstrapping phase
  std::chrono::milliseconds bootDura(WaitBeforeStart);
  std::unique_lock<std::mutex> guard(m_stopped_lock);
  m_stopped = false;
  m_condition.wait_for(guard, bootDura, [this] { return m_stopped; });

  if (!m_stopped) {
    Logger::Info("Host health monitor starts working.");
  }

  std::chrono::milliseconds dura(UpdateFreq);

  // periodically update monitored metrics
  while (!m_stopped) {
    HealthLevel newStatus = evaluate();
    notifyObservers(newStatus);
    m_condition.wait_for(guard, dura, [this] { return m_stopped; });
  }
}