Esempio n. 1
0
void consumer(int num){
	//pop valus if available (num identifies the consumer)
	while(true){
		int val;
		{
			std::unique_lock<std::mutex> ul(queueMutex);
			queueConVar.wait(ul, []{return !queue.empty();});
			val = queue.front();
			queue.pop();
		}//release lock
		printf("consumer %d : %d,\n", num, val);
	}
}
Esempio n. 2
0
void print(std::queue<vec> s)
{
  int sizeQueue=s.size();
  //DispVal(sizeQueue);
 
    while(sizeQueue!=0){
      vec x= s.front();
      s.pop();
      std::cout << x << "\n";
      sizeQueue--;
    }
    return;
}
Esempio n. 3
0
    virtual uavcan::int16_t receive(uavcan::CanFrame& out_frame, uavcan::MonotonicTime& out_ts_monotonic,
                                    uavcan::UtcTime& out_ts_utc, uavcan::CanIOFlags& out_flags)
    {
        assert(this);
        if (loopback.empty())
        {
            EXPECT_TRUE(rx.size());        // Shall never be called when not readable
            if (rx_failure)
            {
                return -1;
            }
            if (rx.empty())
            {
                return 0;
            }
            const FrameWithTime frame = rx.front();
            rx.pop();
            out_frame = frame.frame;
            out_ts_monotonic = frame.time;
            out_ts_utc = frame.time_utc;
            out_flags = frame.flags;
        }
        else
        {
            out_flags |= uavcan::CanIOFlagLoopback;
            const FrameWithTime frame = loopback.front();
            loopback.pop();
            out_frame = frame.frame;
            out_ts_monotonic = frame.time;
            out_ts_utc = frame.time_utc;
        }

        // Let's just all pretend that this code is autogenerated, instead of being carefully designed by a human.
        if (out_ts_utc.isZero())
        {
            out_ts_utc = enable_utc_timestamping ? iclock.getUtc() : uavcan::UtcTime();
        }
        return 1;
    }
				int pop(T *out)
				{
					std::unique_lock<std::mutex> lock(m_mutex);				
				    while (isEmpty()) m_condNotFull.wait(lock);
					
					m_rwmut.lock();
						*out = m_que.front();
						m_que.pop();
					m_rwmut.unlock();
					
					m_condNotEmpty.notify_all();					
					return 0;
				}
Esempio n. 5
0
int getVictim(frame_t *victim){
	switch(CUR_ALGO){
		case FIFO:
			*victim = fifo_queue.front();//get victim
			fifo_queue.pop();//move queue forward
			break;
		case LRU:
			*victim = lru_queue.front();//get victim
			lru_queue.pop();//move queue forward
			break;
		case CLOCK:
			clockVictim(victim);
			break;
		case ECLOCK:
			clockVictim(victim);
			break;
		default:
			return -1; //invalid, use default
			break;
	}
	return 0;
}
void MockRDMController::RunFullDiscovery(RDMDiscoveryCallback *callback) {
  CPPUNIT_ASSERT(m_expected_discover_calls.size());
  expected_discovery_call call = m_expected_discover_calls.front();
  m_expected_discover_calls.pop();
  CPPUNIT_ASSERT(call.full);

  if (call.uids) {
    callback->Run(*call.uids);
  } else {
    CPPUNIT_ASSERT(!m_discovery_callback);
    m_discovery_callback = callback;
  }
}
void MockRDMController::RunFullDiscovery(RDMDiscoveryCallback *callback) {
  OLA_ASSERT_TRUE(m_expected_discover_calls.size());
  expected_discovery_call call = m_expected_discover_calls.front();
  m_expected_discover_calls.pop();
  OLA_ASSERT_TRUE(call.full);

  if (call.uids) {
    callback->Run(*call.uids);
  } else {
    OLA_ASSERT_FALSE(m_discovery_callback);
    m_discovery_callback = callback;
  }
}
Esempio n. 8
0
void processPlayerCommandQueue(std::queue<narf::PlayerCommand>& q) {
	switch (connectState) {
	case ConnectState::Unconnected:
		while (!q.empty()) {
			q.front().exec(world);
			q.pop();
		}
		break;

	case ConnectState::Connected:
		while (!q.empty()) {
			sendPlayerCommand(q.front());
			q.pop();
		}
		enet_host_flush(client); // TODO: probably not necessary?
		break;

	case ConnectState::Connecting:
		// discard command
		break;
	}
}
Esempio n. 9
0
	bool pop(T &item)
	{
		item = NULL;

		std::unique_lock<std::mutex> lock(mutex_);

		if (queue_.empty()) return false;

		item = queue_.front();
		queue_.pop();

		return true;
	}
    // Get data from the queue. Wait for data if not available
  T Dequeue(){
    // Acquire lock on the queue
    boost::unique_lock<boost::mutex> lock(m_mutex);

    // When there is no data, wait till someone fills it.
    // Lock is automatically released in the wait and obtained
    // again after the wait
    while (m_queue.size()==0) m_cond.wait(lock);

    // Retrieve the data from the queue
    T result=m_queue.front(); m_queue.pop();
    return result;
  } // Lock is automatically released here
Esempio n. 11
0
	/**
		回收一个对象容器
	*/
	void reclaimObject(std::queue<T*>& objs)
	{
		mutex_.lockMutex();
		
		while(!objs.empty())
		{
			T* t = objs.front();
			objs.pop();
			reclaimObject_(t);
		}

		mutex_.unlockMutex();
	}
Esempio n. 12
0
int main(void)
{
	scanf("%d", &spies);
	for(int s = 0; s < spies; ++ s)
	{
		scanf("%d", &spy);
		-- spy;
		++ followed[spy];
		following[s] = spy;
	}

	for(int s = 0; s < spies; ++ s)
		if(!followed[s])
			que.push(s);

	while(!que.empty())
	{
		spy = que.front();
		que.pop();

		if(following[spy] == -1)
			continue;

		if(following[following[spy]] == -1)
			continue;

		++ result;
		if(!-- followed[following[following[spy]]])
			que.push(following[following[spy]]);

		following[following[spy]] = -1;
		following[spy] = -1;
	}

	for(int s = spy = 0, count, o; s < spies; spy = ++ s)
	{
		count = 0;
		while(following[spy] != -1)
		{
			++ count;
			o = spy;
			spy = following[spy];
			following[o] = -1;
		}

		result += count / 2;
	}

	printf("%d\n", result);
	return 0;
}
Esempio n. 13
0
void CConfigDialog::OnTimer(UINT nIDEvent) 
{
	if (nIDEvent==1001)
	{
		KillTimer(1001);
		CMemReaderProxy reader;
		switch (reader.getConnectionState())
		{
		case 0: 
				if (loginTime){
					char buf[128];
					if (loginTime-time(NULL)>=0) sprintf(buf,"Connection status: waiting to log in %d seconds.",loginTime-time(NULL));
					else sprintf(buf,"Connection status: trying to log in for %d seconds.",time(NULL)-loginTime);
					m_status.SetWindowText(buf);break;
				}
				m_status.SetWindowText("Connection status: not connected");break;
		case 1: m_status.SetWindowText("Connection status: opening to login server");break;
		case 2: m_status.SetWindowText("Connection status: connecting to login server");break;
		case 3: m_status.SetWindowText("Connection status: disconnecting from login server");break;
		case 4: m_status.SetWindowText("Connection status: connected to login server");break;
		case 5: m_status.SetWindowText("Connection status: opening");break;
		case 6: m_status.SetWindowText("Connection status: connecting");break;
		case 7: m_status.SetWindowText("Connection status: disconnecting");break;
		case 8: m_status.SetWindowText("Connection status: connected");break;
		default: m_status.SetWindowText("Connection status: unknown");break;
		};

		EnterCriticalSection(&QueueCriticalSection);
		while (!queue2.empty())
		{
			char timeBuf[256];
			char *msg = queue2.front();
			queue2.pop();
			m_debug.InsertItem(0,"");
			time_t nowSec = time(NULL);
			struct tm *now = localtime(&nowSec);
			sprintf(timeBuf,"%d:%d:%d",now->tm_hour,now->tm_min,now->tm_sec);
			m_debug.SetItemText(0,0,timeBuf);
			m_debug.SetItemText(0,1,msg);			
			if (m_debug.GetItemCount()>100)
			{
				m_debug.DeleteItem(m_debug.GetItemCount());
			}
			delete msg;
		}
		LeaveCriticalSection(&QueueCriticalSection);
		SetTimer(1001,500,NULL);
	}
	
	CDialog::OnTimer(nIDEvent);
}
Esempio n. 14
0
int flip()
{
	int loop_count = 0;

	while(!stat_queue.empty())
	{
		loop_count++;
		unsigned long stat = stat_queue.front();
		stat_queue.pop();
		if(finished(stat))
		{
			int steps = 0;
			while(path[stat] != 0)
			{
				++steps;
				stat = path[stat];
			}
			printf("%d", steps);
			return 0;
		}
		int xPos, yPos;
		for(xPos = 0; xPos < N; ++xPos)
		{
			for(yPos = 0; yPos < N; ++yPos)
			{
				int i;
				std::bitset < 16 > next_stat(stat);
				for(i = 0; i < 5; ++i)
				{
					if(is_legal_position(xPos + move[i][0], yPos + move[i][1]) )
					{
						next_stat.flip((xPos + move[i][0]) * N + (yPos + move[i][1]) );
					}

				}

				//printf("%d\n", next_stat.to_ulong());
				unsigned long num_status = next_stat.to_ulong();
				if(!status_set.test(num_status))
				{
					status_set.set(num_status);
					//remember where current status comes from.
					path[num_status] = stat;
					stat_queue.push(num_status);
				}
			}
		}
	}
	printf("Impossible");
	return -1;
}
Esempio n. 15
0
  //------------------------------------------------------------------------------------------------------------------------------------
  bool __stdcall spiReceive(SOCKADDR **senderPeer, char **data, DWORD *databytes)
  {
    INTERLOCKED;
//    DropMessage(0, "spiReceive %d", GetCurrentThreadId());
    // Passes pointers from queued receive data to storm

    *senderPeer = nullptr;
    *data       = nullptr;
    *databytes  = 0;

    try
    {
      pluggedNetwork->receive();

      while(true)
      {
        // check if packets available
        if(incomingGamePackets.empty())
        {
          SErrSetLastError(STORM_ERROR_NO_MESSAGES_WAITING);
          return false;
        }

        // save the packet before removing it from queue
        GamePacket *loan = new GamePacket();
        *loan = incomingGamePackets.front();
        incomingGamePackets.pop();

        // paket outdated?
        if(GetTickCount() > loan->timeStamp + 10000)
        {
          DropMessage(1, "Dropped outdated packet (%dms delay)", GetTickCount() - loan->timeStamp);
          continue;
        }

        // give saved data to storm
        *senderPeer =&loan->sender;
        *data       = loan->data;
        *databytes  = loan->packetSize;
//        DropMessage(0, "R %s", sprintfBytes(*data, *databytes));
//        DropMessage(0, "Received storm packet %d bytes", *databytes);
        break;
      }
    }
    catch(GeneralException &e)
    {
      DropLastError("spiLockGameList failed: %s", e.getMessage());
      return false;
    }
    return true;
  }
Esempio n. 16
0
void
GraphTools::__BFS( std::queue< raft::kernel* > &queue,
                   std::set< raft::kernel*   > &visited_set,
                   vertex_func                 func,
                   void                        *data )
{
#if 0
   while( queue.size() > 0 )
   {
      auto *source( queue.front() );
      queue.pop();
      /** iterate over all out-edges **/
      /** 1) get lock **/
      std::lock_guard< std::mutex > lock( source->output.portmap.map_mutex );
      /** 2) get map **/
      std::map< std::string, PortInfo > &map_of_ports( source->output.portmap.map );
      /** 3) visit kernel **/
      func( *source, data );
      /** 4) add children to queue **/
      for( auto &port : map_of_ports )
      {
         PortInfo &source( port.second );
         /** get dst edge to call function on **/
         if( source.other_kernel != nullptr  )
         {
            PortInfo &dst( 
               source.other_kernel->input.getPortInfoFor( source.other_name ) );
            func( source, dst, data );
         }
         else
         if( connected_error )
         {
            std::stringstream ss;
            ss << "Unconnected port detected at " << 
               common::printClassName( *k ) <<  
                  "[ \"" <<
                  source.my_name << " \"], please fix and recompile.";
            throw PortException( ss.str() );
         }
         /** if the dst kernel hasn't been visited, visit it **/
         if( visited_set.find( source.other_kernel ) == visited_set.end() )
         {
            queue.push( source.other_kernel );
            visited_set.insert( source.other_kernel ); 
         }
      }
   }
   return;
#endif
   assert( false ); /** FIXME: error above with virtual function 'func', fix in a bit **/
}
Esempio n. 17
0
int get_image(cv::Mat& im, const cv::Mat& mapping, bool rotate, int socket,
              const std::string& fname, int& ncount)
{
    int nframes = 0;
    /* empty the acquired frame buffer */
    while (acq_frame_buffer.size() > 0) {

        int width = acq_frame_buffer.front().width;
        int height = acq_frame_buffer.front().height;
        double timestamp = acq_frame_buffer.front().timestamp;

#ifndef LICKOMETER
        if (fname != "") {
            std::ostringstream jpgname;
            jpgname << fname << std::setfill('0') << std::setw(7) << ncount << ".jpg";
            pthread_mutex_lock( &save_buffer_mutex );
            save_frame_buffer.push(saveframe(acq_frame_buffer.front().data,
                                             width, height, timestamp, jpgname.str()));
            pthread_mutex_unlock( &save_buffer_mutex );
        }
#endif

        pthread_mutex_lock( &acq_buffer_mutex );
        im = cv::Mat(cv::Size(width, height), CV_8UC1, &acq_frame_buffer.front().data[0]).clone();
        if (rotate) {
            cv::Mat cpim = im.clone();
            cv::warpAffine(cpim, im, mapping, im.size());
        }
        acq_frame_buffer.pop();
        pthread_mutex_unlock( &acq_buffer_mutex );
        if (fname != "") {
            write_send(socket, timestamp, fname, ncount);
        }

        nframes++;
    }
    return nframes;
}
void writeThread(void *)
{
	while (stpReceived == 0)
	{
		if (_kbhit()) {						
			char key = _getch();
			if (key == 'q' || key == 'Q') {
				stpReceived = 1;
			}
		}

		WaitForSingleObject(myMutex,INFINITE);		//ownMutex?	
		//std::cout << "\nWrite thread owns Mutex" << std::endl;			
		if (!myQueue.empty()) //while there is still data in the queue keep writing cubes
		{
			//std::cout << "\nQueue not empty" << std::endl;
			std::pair<unsigned short *, int> myData = myQueue.front();
			//std::cout << "\nGot pair from queue" << std::endl; 
			myQueue.pop();
			//std::cout << "\nPop data from queue" << std::endl;
			ReleaseMutex(myMutex);
			//std::cout << "\nRelased Mutex" << std::endl;
			makeCube(myData);
			//std::cout << "\nmakeCube called" << std::endl;
		}
		else
		{
		ReleaseMutex(myMutex);						
		Sleep(1000);
		}
	}
	while (!myQueue.empty()) //while there is still data in the queue keep writing cubes
	{
		std::pair<unsigned short *, int> myData = myQueue.front();
		myQueue.pop();
		makeCube(myData);
	} 
}
Esempio n. 19
0
int solve2( std::pair<int, int> e, int dep[max_h][max_w] )
{

  int depth = 1;
  for( int i = 0; i < 2 * h + 1; ++i )
    for( int j = 0; j < 2 * w + 1; ++j )
      visited[i][j] = false;
  
  q.push( e );
  dep[e.first][e.second] = depth;
  visited[e.first][e.second] = true;
  
  while( !q.empty() ){
    int size = q.size();
        depth++;

    while( size-->0 ){
      std::pair<int, int> t = q.front();
      q.pop();
      int i = t.first;
      int j = t.second;
      //      std::cout << depth << ": " << i << " " << j << std::endl;
      if( i - 2 > 0 && maze[i-1][j] != '*' && !visited[i-2][j]
	  && dep[i-2][j] >= depth){
	q.push( std::make_pair( i - 2, j ) );
	dep[i-2][j] = depth;
	visited[i-2][j] = true;
      }
      if( j + 2 < 2 * w && maze[i][j+1] != '*' && !visited[i][j+2]
	  && dep[i][j+2] >= depth){
	q.push( std::make_pair( i, j + 2 ) );
	dep[i][j+2] = depth;
	visited[i][j+2] = true;
      }
      if( i + 2 < 2 * h && maze[i+1][j] != '*' && !visited[i+2][j]
	  && dep[i+2][j] >= depth){
	q.push( std::make_pair( i+2, j ) );
	dep[i+2][j] = depth;
	visited[i+2][j] = true;
      }
      if( j - 2 > 0 && maze[i][j-1] != '*'&& !visited[i][j-2]
	  && dep[i][j-2] >= depth ){
	q.push( std::make_pair( i, j - 2 ) );
	dep[i][j-2] = depth;
	visited[i][j-2] = true;
      }
    }
  }
  return depth - 1;
}
 // Thread safe receive
 proton::message receive() {
     std::unique_lock<std::mutex> l(lock_);
     // Wait for buffered messages
     while (!closed_ && (!work_queue_ || buffer_.empty())) {
         can_receive_.wait(l);
     }
     if (closed_) throw closed("receiver closed");
     proton::message m = std::move(buffer_.front());
     buffer_.pop();
     // Add a lambda to the work queue to call receive_done().
     // This will tell the handler to add more credit.
     work_queue_->add([=]() { this->receive_done(); });
     return m;
 }
Esempio n. 21
0
	/**@brief Get a chunk of values, less locking
	 *
	 * @param vals the vector to fill with several values from the queue
	 * @param num the number of vals to get
	 * @return whether any values were gotten
	 */
	bool getVals(std::vector<T> & vals, uint32_t num) {
		vals.clear();
		std::lock_guard<std::mutex> lock(mut_);
		if (!vals_.empty()) {
			uint32_t count = 0;
			while(!vals_.empty() && count < num){
				vals.emplace_back(vals_.front());
				vals_.pop();
				++count;
			}
			return true;
		}
		return false;
	}
Esempio n. 22
0
void AVL_Tree::levelTraversal(Node* n, std::queue<Node*> Q)
{
	Node* h;
	while(!Q.empty())
	{
		h = Q.front();
		Q.pop();
		std::cout << h -> getCityName()<<" X:"<< h -> getXCoordinate()<<", Y:" << h -> getYCoordinate() << "\n";
		if(h -> getLeft() != NULL)
			Q.push(h -> getLeft());
		if(h -> getRight() != NULL)
			Q.push(h -> getRight());
	}
}//end bfs
Esempio n. 23
0
size_t QueuingAudioStreamImpl::readBuffer(int16 *buffer, const size_t numSamples) {
	Common::StackLock lock(_mutex);
	size_t samplesDecoded = 0;

	while (samplesDecoded < numSamples && !_queue.empty()) {
		AudioStream *stream = _queue.front()._stream;

		const size_t n = stream->readBuffer(buffer + samplesDecoded, numSamples - samplesDecoded);
		if (n == kSizeInvalid)
			return kSizeInvalid;

		samplesDecoded += n;

		if (stream->endOfData()) {
			StreamHolder tmp = _queue.front();
			_queue.pop();
			if (tmp._disposeAfterUse)
				delete stream;
		}
	}

	return samplesDecoded;
}
Esempio n. 24
0
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; ++ i) {
        scanf("%d%d", a + i, b + i);
        a[i] --;
        b[i] --;
        add_edge(i);
    }
    int edge_count = m;
    memset(mark, 0, sizeof(mark));
    memset(exists, 0, sizeof(exists));
    for (int i = 0; i < n; ++ i) {
        enqueue(i);
    }
    for (int total = n; total > 3; total --) {
        int u = queue.front();
        queue.pop();
        int v, w;
        {
            Iterator iter = edges[u].begin();
            v = iter->first;
            remove_edge(iter->second);
            iter ++;
            w = iter->first;
            remove_edge(iter->second);
        }
        int id = get_edge(v, w);
        if (id == -1) {
            a[edge_count] = v;
            b[edge_count] = w;
            add_edge(edge_count ++);
        } else {
            mark[id] = true;
        }
        enqueue(v);
        enqueue(w);
    }
    for (int i = 0; i < n; ++ i) {
        edges[i].clear();
    }
    for (int i = 0; i < m; ++ i) {
        if (!mark[i]) {
            add_edge(i);
        }
    }
    int prev = 0;
    int now = n;
    foreach (iter, edges[0]) {
        now = std::min(now, iter->first);
    }
Esempio n. 25
0
bool EmergeThread::popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata)
{
	MutexAutoLock queuelock(m_emerge->m_queue_mutex);

	if (m_block_queue.empty())
		return false;

	*pos = m_block_queue.front();
	m_block_queue.pop();

	m_emerge->popBlockEmergeData(*pos, bedata);

	return true;
}
Esempio n. 26
0
bool pop()
{
    boost::intrusive_ptr<Message> msg = queue->get().payload;
    if (msg) {
        QueuedMessage qm;
        qm.payload = msg;
        queue->dequeue(0, qm);
        BOOST_CHECK_EQUAL(ids.front(), msg->getProperties<MessageProperties>()->getMessageId());
        ids.pop();
        return true;
    } else {
        return false;
    }
}
JNIEXPORT jobject JNICALL scsynth_android_getMessage ( JNIEnv* env, jobject obj )
{
	if (!scsynthMessages.empty()) {
		std::string firstMessage (scsynthMessages.front());
		scsynthMessages.pop();
		char* data = new char[firstMessage.length()+1];
		int length (firstMessage.copy(data,firstMessage.length()));
		data[length] = 0;
		jobject oscMessage (convertMessageToJava(env, data, length));
		delete[] data;
		return oscMessage;
	}
	return NULL;
}
Esempio n. 28
0
void UpdateEntitySpawns()
{
	if (!WaitingToSpawn.empty())
	{
		EntitySpawn currSpawn = WaitingToSpawn.front();

		if (STREAMING::HAS_MODEL_LOADED(currSpawn.modelHash))
		{
			currSpawn.spawnFunction();
			STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(currSpawn.modelHash);
			WaitingToSpawn.pop();
		}
	}
}
Esempio n. 29
0
 void sound_icon_inserter::on_input()
 {
   if(!points.empty())
     {
       int next_time=points.front()->get_time();
       if((next_time!=-1)&&(next_time<=time))
         {
           points.pop();
           insertion=(*icon)();
         }
     }
   output=input;
   time+=input.size();
 }
Esempio n. 30
0
///////////////////////////////////////////////////////
//
// Function: GetNextInputEvent
//
// Parameters: event - a pointer to the input event that will be 
//									modified.
//
// Action: Call this function to get the next input event from the queue
//
// Returns: true - a new event was found
//					false - no new events found.
//
///////////////////////////////////////////////////////
bool GetNextInputEvent(INPUT_EVENT* event)
{
	if ( g_qInputEvents.size() > 0 ) 
	{
		*event = g_qInputEvents.front();
		//now remove the event at the head of the list...
		g_qInputEvents.pop();
		return true;
	}
	else 
	{
		return false;
	}
}