void* consumer(void* arg) {
	while(true) {
		pthread_mutex_lock(&queue_lock);
		while(queue.size() == 0) {
			pthread_cond_wait(&consumer_condvar, &queue_lock);
		}
    int front = queue.front();
    queue.pop();
		assert(front == 123);
		consumed++;
		pthread_mutex_unlock(&queue_lock);
		pthread_cond_signal(&producer_condvar);
		COZ_PROGRESS;
	}
}
Esempio n. 2
0
void dijkstra()
{
    q.push(1);
    d[1]=0;
    while(!q.empty())
    {
        aux=q.front();q.pop();
        for(unsigned int i = 0; i < a[aux].size(); ++i)
        {
            cost=a[aux][i].c; nod=a[aux][i].x;
            if(d[nod]>d[aux]+cost) 
                {d[nod]=d[aux]+cost; q.push(nod);}
        }
    }
}
Esempio n. 3
0
        breadthfirst_iterator& operator++() {
            if (node(m_t, m_n).child_head)
                m_q.push(node(m_t, m_n).child_head);

            if (node(m_t, m_n).next)
                m_t = node(m_t, m_n).next;
            else if (!m_q.empty()) {
                m_t = m_q.front();
                m_q.pop();
            } else {
                m_t = 0;
            }

            return *this;
        }
Esempio n. 4
0
bool GetAvailableSock(sf::SocketTCP& sock_to_fill)
{
	bool sock_filled = false;

	std::lock_guard<std::mutex> lk(cs_gba);

	if (!waiting_socks.empty())
	{
		sock_to_fill = waiting_socks.front();
		waiting_socks.pop();
		sock_filled = true;
	}

	return sock_filled;
}
Esempio n. 5
0
// Call this under frameCommandLock.
static void ProcessFrameCommands(JNIEnv *env) {
	while (!frameCommands.empty()) {
		FrameCommand frameCmd;
		frameCmd = frameCommands.front();
		frameCommands.pop();

		WLOG("frameCommand! '%s' '%s'", frameCmd.command.c_str(), frameCmd.params.c_str());

		jstring cmd = env->NewStringUTF(frameCmd.command.c_str());
		jstring param = env->NewStringUTF(frameCmd.params.c_str());
		env->CallVoidMethod(nativeActivity, postCommand, cmd, param);
		env->DeleteLocalRef(cmd);
		env->DeleteLocalRef(param);
	}
}
Esempio n. 6
0
 // Returns FALSE if message not read, TRUE if it was read.  Will always return TRUE if "blocking" is set.
bool CDIF_Queue::Read(CDIF_Message *message, bool blocking)
{
  if(!blocking && ze_queue.size() == 0)
  {
     return FALSE;
  }

  MDFND_WaitSemaphore(ze_semaphore);
  MDFND_LockMutex(ze_mutex);
  assert(ze_queue.size() > 0);
  *message = ze_queue.front();
  ze_queue.pop();
  MDFND_UnlockMutex(ze_mutex);
  return TRUE;
}
Esempio n. 7
0
void UpdateRunLoopAndroid(JNIEnv *env) {
	NativeUpdate();

	NativeRender(graphicsContext);
	time_update();

	std::lock_guard<std::mutex> guard(frameCommandLock);
	if (!nativeActivity) {
		while (!frameCommands.empty())
			frameCommands.pop();
		return;
	}
	// Still under lock here.
	ProcessFrameCommands(env);
}
Esempio n. 8
0
BOOL __stdcall Hook_ReadFile(HANDLE hFile,
							 LPVOID lpBuffer,
							 DWORD nNumberOfBytesToRead,
							 LPDWORD lpNumberOfBytesRead,
							 LPOVERLAPPED lpOverlapped)
{


	if (hFile != hConnection) {
		return __ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
	}
#if DEBUG_API
	logmsg("ReadFile(%x, %p, %d, %p, %p)\n",
		hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
#endif

	if (replyBuffer.size())
	{
		if (nNumberOfBytesToRead >= replyBuffer.size())
			nNumberOfBytesToRead = replyBuffer.size();
		*lpNumberOfBytesRead = nNumberOfBytesToRead;
		BYTE *ptr = (BYTE*) lpBuffer;
		for (DWORD i=0; i < nNumberOfBytesToRead; i++) {
			if (!replyBuffer.empty()) {
				*ptr++ = replyBuffer.front();
				replyBuffer.pop();
			} else {
				*lpNumberOfBytesRead = i;
				break;
			}
		}
#if LOG_IO_STREAM
	//	logmsg("Lidos %d\n", nNumberOfBytesToRead);
		ptr = (BYTE*) lpBuffer;
		logmsg("SD:  ");
		for (DWORD i=0; i < nNumberOfBytesToRead; i++) {
			logmsg_nt("%02X ", (DWORD) *ptr++);
		}
		logmsg_nt("\n");
#endif
	} else {
		*lpNumberOfBytesRead = 0;
		return TRUE;
	}


	return TRUE;
}
Esempio n. 9
0
    void BFS() {
        memset(dist, 0x3f, sizeof dist);
        Q.push(t);
        dist[t] = 0;
 
        while( !Q.empty() ) {
            int o = Q.front(); Q.pop();
            for(int i=0; i < G[o].size(); ++i) {
                edge& e = edges[G[o][i]];
                if( dist[e.to] == INF && e.cap == 0 ) {
                    dist[e.to] = dist[o] + 1;
                    Q.push(e.to);
                }
            }
        }
    }
Esempio n. 10
0
    bool wait_and_pop(T& data, std::chrono::microseconds waitingTime)
    {
        std::unique_lock<std::mutex>     lockHandle(mutexHandle);

        if (condFlag.wait_for(lockHandle, waitingTime,
                              [this]{return !queueHandle.empty();})) {
            data = std::move(*queueHandle.front());
            queueHandle.pop();
            condFlag.notify_all();

            return true;
        }
        else {
            return false;
        }
    }
Esempio n. 11
0
File: AIO.c Progetto: Nadasua/HBNews
		bool queue_pop(TaskItem& item)
		{
			pthread_mutex_lock(&m_mutex);
			if(w_items.empty())
			{
				pthread_mutex_unlock(&m_mutex);
				return false;
			}
			item.start_offset=w_items.front().start_offset;
			item.size=w_items.front().size;
			item.buffer=w_items.front().buffer;
			item.sem=w_items.front().sem;
			w_items.pop();
			pthread_mutex_unlock(&m_mutex);
			return true;
		}
Esempio n. 12
0
static void consume()
{
    while(true)
    {
        boost::mutex::scoped_lock lock(mutex);

        if(messages.empty())
        {
            out << "Waiting..." << std::endl;
            cond.wait(lock);
        }

        out << "Got " << messages.front() << std::endl;
        messages.pop();
    }
}
Esempio n. 13
0
	// get next buffer element from the pool
	BYTE* next()
	{
		BYTE* next_buffer;
		if (!m_queue.empty())
		{
			next_buffer = m_queue.front().release();
			m_queue.pop();
		}
		else
		{
			next_buffer = new BYTE[m_buffersize];
			memset(next_buffer, 0, m_buffersize);
		}

		return next_buffer;
	}
Esempio n. 14
0
    static float getFps()
    {
        static std::queue<int64> time_queue;

        int64 now = cv::getTickCount();
        int64 then = 0;
        time_queue.push(now);

        if (time_queue.size() >= 2)
            then = time_queue.front();

        if (time_queue.size() >= 25)
            time_queue.pop();

        return time_queue.size() * (float)cv::getTickFrequency() / (now - then);
    }
Esempio n. 15
0
                void thread_fn()
                {
					while (enabled)
					{
						std::unique_lock<std::mutex> locker(mutex); 
						cv.wait(locker, [&](){ return !fqueue.empty() || !enabled; });
						while(!fqueue.empty())
						{
							fn_type fn = fqueue.front(); 
							fqueue.pop();
							locker.unlock();
							fn();
							locker.lock();
						}                              
					}
                }
Esempio n. 16
0
void EmergeThread::cancelPendingItems()
{
	MutexAutoLock queuelock(m_emerge->m_queue_mutex);

	while (!m_block_queue.empty()) {
		BlockEmergeData bedata;
		v3s16 pos;

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

		m_emerge->popBlockEmergeData(pos, &bedata);

		runCompletionCallbacks(pos, EMERGE_CANCELLED, bedata.callbacks);
	}
}
Esempio n. 17
0
void LuaVFSDownload::Update()
{
	assert(Threading::IsMainThread() || Threading::IsGameLoadThread());
	// only locks the mutex if the queue is not empty
	if (!dlEventQueue.empty()) {
		dlEventQueueMutex.lock();
		dlEvent* ev;
		while (!dlEventQueue.empty()) {
			ev = dlEventQueue.front();
			dlEventQueue.pop();
			ev->processEvent();
			SafeDelete(ev);
		}
		dlEventQueueMutex.unlock();
	}
}
AddressNode AddressNodeFactory::Make(const string& firstName, const string& lastName)
{
    static int nextID = 1;

    int newID = 0;
    if (availableIDs.empty())
    {
        newID = nextID++;
    }
    else
    {
        newID = availableIDs.front();
        availableIDs.pop();
    }
    return AddressNode(firstName, lastName, newID);
}
Esempio n. 19
0
//save cloud thread, save all remaining cloud in the queue
void saveCloud()
{
	while (running)
	{

		while (!cloud_que.empty())
		{
			std::pair<pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr, int> first_cloud;
			first_cloud = cloud_que.front();

			std::cout << first_cloud.second << std::endl;
			pcl::io::savePCDFileBinary(path+"/"+int2string(first_cloud.second) + ".pcd", *first_cloud.first);
			cloud_que.pop();
		}
	}
}
Esempio n. 20
0
	void traverse_graph (std::function<void(FAO*)> node_fn, bool forward) {
		/* Traverse the graph and apply the given function at each node.

		   forward: Traverse in standard or reverse order?
		   node_fn: Function to evaluate on each node.
		*/
		FAO *start;
		if (forward) {
			start = start_node;
		} else {
			start = end_node;
		}
		ready_queue.push(start);
		while (!ready_queue.empty()) {
			FAO* curr = ready_queue.front();
			ready_queue.pop();
			// Evaluate the given function on curr.
			node_fn(curr);
			eval_map[curr]++;
			std::vector<int> child_edges;
			if (forward) {
				child_edges = curr->output_edges;
			} else {
				child_edges = curr->input_edges;
			}
			/* If each input has visited the node, it is ready. */
			for (auto edge_idx : child_edges) {
				auto edge = edges[edge_idx];
				FAO *node;
				if (forward) {
					node = edge.second;
				} else {
					node = edge.first;
				}
				eval_map[node]++;
				size_t node_inputs_count;
				if (forward) {
					node_inputs_count = node->input_edges.size();
				} else {
					node_inputs_count = node->output_edges.size();
				}
				if (eval_map[node] == node_inputs_count)
					ready_queue.push(node);
			}
		}
		eval_map.clear();
	}
Esempio n. 21
0
// JavaEGL
extern "C" void Java_org_ppsspp_ppsspp_NativeRenderer_displayRender(JNIEnv *env, jobject obj) {
	static bool hasSetThreadName = false;
	if (!hasSetThreadName) {
		hasSetThreadName = true;
		setCurrentThreadName("AndroidRender");
	}

	if (renderer_inited) {
		// TODO: Look into if these locks are a perf loss
		{
			lock_guard guard(input_state.lock);

			input_state.pad_lstick_x = left_joystick_x_async;
			input_state.pad_lstick_y = left_joystick_y_async;
			input_state.pad_rstick_x = right_joystick_x_async;
			input_state.pad_rstick_y = right_joystick_y_async;

			UpdateInputState(&input_state);
		}
		NativeUpdate(input_state);

		{
			lock_guard guard(input_state.lock);
			EndInputState(&input_state);
		}

		NativeRender(graphicsContext);
		time_update();
	} else {
		ELOG("BAD: Ended up in nativeRender even though app has quit.%s", "");
		// Shouldn't really get here. Let's draw magenta.
		// TODO: Should we have GL here?
		glDepthMask(GL_TRUE);
		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
		glClearColor(1.0, 0.0, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	}

	lock_guard guard(frameCommandLock);
	if (!nativeActivity) {
		while (!frameCommands.empty())
			frameCommands.pop();
		return;
	}

	ProcessFrameCommands(env);
}
Esempio n. 22
0
    bool wait_and_pop(T& data, boost::posix_time::microseconds waitTime)
    {
        boost::system_time            timeout = boost::get_system_time() + waitTime;
        boost::mutex::scoped_lock     lockHandle(mutexHandle);

        if (condFlag.timed_wait(lockHandle, timeout,
                                isEmpty(&queueHandle))) {
            data = queueHandle.front();
            queueHandle.pop();
            condFlag.notify_all();

            return true;
        }
        else {
            return false;
        }
    }
	std::shared_ptr<T> getNext()
	{
		std::unique_lock<std::mutex> lock(mutex);
		condition.wait(lock, [this]() -> bool 
		{
			return !queue.empty() || isClosed;
		});

		if (!queue.empty())
		{
			auto ptr = queue.front();
			queue.pop();
			return ptr;
		}
		
		return std::shared_ptr<T>();
	}	
Esempio n. 24
0
	T pop()
	{
		boost::mutex::scoped_lock lock(_mutex);

		while(_queue.empty())
		{
			_conditionVar.wait(lock);
		}

		T result =_queue.front();
		_queue.pop();

		lock.unlock();
		_conditionVar.notify_one();

		return result;
	}
Esempio n. 25
0
	virtual safe_ptr<basic_frame> receive(int) override
	{
		auto format_desc = consumer_->get_video_format_desc();

		if(frame_buffer_.size() > 0)
		{
			auto frame = frame_buffer_.front();
			frame_buffer_.pop();
			return last_frame_ = frame;
		}
		
		auto read_frame = consumer_->receive();
		if(!read_frame || read_frame->image_data().empty())
			return basic_frame::late();		

		frame_number_++;
		
		core::pixel_format_desc desc;
		bool double_speed	= std::abs(frame_factory_->get_video_format_desc().fps / 2.0 - format_desc.fps) < 0.01;		
		bool half_speed		= std::abs(format_desc.fps / 2.0 - frame_factory_->get_video_format_desc().fps) < 0.01;

		if(half_speed && frame_number_ % 2 == 0) // Skip frame
			return receive(0);

		desc.pix_fmt = core::pixel_format::bgra;
		desc.planes.push_back(core::pixel_format_desc::plane(format_desc.width, format_desc.height, 4));
		auto frame = frame_factory_->create_frame(this, desc, read_frame->multichannel_view().channel_layout());

		bool copy_audio = !double_speed && !half_speed;

		if (copy_audio)
		{
			frame->audio_data().reserve(read_frame->audio_data().size());
			boost::copy(read_frame->audio_data(), std::back_inserter(frame->audio_data()));
		}

		fast_memcpy(frame->image_data().begin(), read_frame->image_data().begin(), read_frame->image_data().size());
		frame->commit();

		frame_buffer_.push(frame);	
		
		if(double_speed)	
			frame_buffer_.push(frame);

		return receive(0);
	}	
Esempio n. 26
0
    // 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. 27
0
void printAll(){
  if(teste > 1)
    printf("\n");
  printf("Teste %d\n", teste);

  for(int i = 0; i <= n;i++){
    if(vertexList[i].countDistance <= p && i != s && vertexList[i].countDistance != 0)
      queueVertex.push(i);
  }

  while(!queueVertex.empty()){
    printf("%d ", queueVertex.front());
    queueVertex.pop();
  }

  printf("\n");
}
Esempio n. 28
0
void 
GraphTools::__BFS( std::queue< raft::kernel* > &queue,
                   std::set<   raft::kernel* > &visited_set,
                   edge_func                   func,
                   void                        *data,
                   bool                        connected_error )
{
   while( queue.size() > 0 )
   {
      auto *k( queue.front() );
      queue.pop();
      /** iterate over all out-edges **/
      /** 1) get lock **/
      std::lock_guard< std::mutex > lock( k->output.portmap.map_mutex );
      /** 2) get map **/
      std::map< std::string, PortInfo > &map_of_ports( k->output.portmap.map );
      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;
}
Esempio n. 29
0
void ProcessTraceQue_onepass(Array2D<elev_t> &dem, Array2D<label_t> &labels, std::queue<GridCellZ<elev_t> > &traceQueue, GridCellZ_pq<elev_t> &priorityQueue, std::vector<std::map<label_t, elev_t> > &my_graph){
  while (!traceQueue.empty()){
    GridCellZ<elev_t> c = traceQueue.front();
    traceQueue.pop();

    bool bInPQ = false;
    for(int n=1;n<=8;n++){
      int nx = c.x+dx[n];
      int ny = c.y+dy[n];

      if(!dem.inGrid(nx,ny))
        continue;

      WatershedsMeet(labels(c.x,c.y),labels(nx,ny),dem(c.x,c.y),dem(nx,ny),my_graph);

      if(labels(nx,ny)!=0)
        continue;    
      
      //The neighbour is unprocessed and higher than the central cell
      if(c.z<dem(nx,ny)){
        traceQueue.emplace(nx,ny,dem(nx,ny));
        labels(nx,ny) = labels(c.x,c.y);
        continue;
      }

      //Decide  whether (nx, ny) is a true border cell
      if (!bInPQ) {
        bool isBoundary = true;
        for(int nn=1;nn<=8;nn++){
          int nnx = nx+dx[n];
          int nny = ny+dy[n];
          if(!dem.inGrid(nnx,nny))
            continue;
          if (labels(nnx,nny)!=0 && dem(nnx,nny)<dem(nx,ny)){
            isBoundary = false;
            break;
          }
        }
        if(isBoundary){
          priorityQueue.push(c);
          bInPQ = true;
        }
      }
    }
  }
}
void MockRDMController::SendRDMRequest(const RDMRequest *request,
                                       RDMCallback *on_complete) {
  CPPUNIT_ASSERT(m_expected_calls.size());
  expected_call call = m_expected_calls.front();
  m_expected_calls.pop();
  CPPUNIT_ASSERT((*call.request) == (*request));
  delete request;
  vector<string> packets;
  if (!call.packet.empty())
    packets.push_back(call.packet);
  if (call.run_callback) {
    on_complete->Run(call.code, call.response, packets);
  } else {
    CPPUNIT_ASSERT(!m_rdm_callback);
    m_rdm_callback = on_complete;
  }
}