zoukankan      html  css  js  c++  java
  • 【C++服务端技术】队列

    链表和锁实现的队列,锁的代码请看其他文章

    #pragma once
    #include <list>
    #include "AutoLock.h"
    
    namespace Extralib
    {
    	namespace SafeQueue
    	{
    		using namespace Thread;
    
    		template<typename Data>
    		class safe_queue
    		{
    		private:
    			std::list<Data> the_queue;
    			pthread_mutex_t m_locker;
    		public:
    			safe_queue()
    			{
    				pthread_mutex_init(&m_locker,NULL); 
    			}
    
    			~safe_queue()
    			{
    				pthread_mutex_destroy(&m_locker);
    			}
    
    			void push_front(const Data& data)
    			{
    				AutoLock locker(m_locker);
    				the_queue.push_front(data);
    			}
    
    			void push(const Data& data)
    			{
    				AutoLock locker(m_locker);
    				the_queue.push_back(data);
    			}
    
    			bool empty() 
    			{
    				AutoLock locker(m_locker);
    				return the_queue.empty();
    			}
    
    			Data& front()
    			{
    				AutoLock locker(m_locker);
    				return the_queue.front();
    			}
    
    			Data const& front() const
    			{
    				AutoLock locker(m_locker);
    				return the_queue.front();
    			}
    			
    			Data& back()
    			{
    				AutoLock locker(m_locker);
    				return the_queue.back();
    			}
    
    			bool try_pop(Data& data)
    			{
    				AutoLock locker(m_locker);
    				if(!the_queue.empty())
    				{
    					data = the_queue.front();
    					the_queue.pop_front();
    					return true;
    				}
    				else
    				{
    					return false;
    				}
    			}
    
    			void exchange(std::list<Data>& result_queue)
    			{
    				AutoLock locker(m_locker);
    				result_queue.swap(the_queue);
    			}
    
    			void pop()
    			{
    				AutoLock locker(m_locker);
    				the_queue.pop_front();
    			}
    
    			void clear()
    			{
    				AutoLock locker(m_locker);
    				the_queue.clear();
    			}
    			
    			int size()
    			{
    				AutoLock locker(m_locker);
    				return the_queue.size();
    			}
    		};
    	}
    }
    
    
  • 相关阅读:
    Ubuntu安装mysql
    Java源码分析:关于 HashMap 1.8 的重大更新(转载)
    idea 设置光标回到上一次位置的快捷键
    2016年总结及2017年计划
    Mac搭建Hadoop源码阅读环境
    Spark sql 在yarn-cluster模式下找不到表
    SecureCRT 无法删除字符
    Flume整合Spark Streaming
    Hbase资料汇总
    maven使用阿里云仓库
  • 原文地址:https://www.cnblogs.com/byfei/p/14104065.html
Copyright © 2011-2022 走看看