【C++服务端技术】消息队列

ThreadWorkUnit.h

#pragma once
#include <queue>
#include <pthread.h>
#include "SafeQueue.h"

namespace Extralib
{
	namespace Thread
	{
		//消息結構體
		struct sWorkItem
		{
			sWorkItem()
			{
				type = 0;
				nDataSize = 0;
				pData = NULL;
				param1 = 0;
			}

			void Set(char type,int param1,int size,char* data)
			{
				this->type = type;
				this->param1 = param1;
				nDataSize = size;
				pData = data;
			}
			
			short type;				//类型取决于不同系统的设定,并不固定
			int param1;				//消息id
			unsigned int nDataSize; //消息包大小
			char* pData;			//消息包
		};

		class ThreadWorkUnit
		{
		public:
			ThreadWorkUnit();
			virtual ~ThreadWorkUnit();

			//线程循环处理函数
			virtual int svc();
			
			void PushItem(const sWorkItem& data);

			bool PopItem(sWorkItem& data);
			bool GetItem(sWorkItem& data);

			void PopAllItems(std::list<sWorkItem>& result_queue);

			bool isStop(){ return m_bStop;}	

			/*
			* 启动工作线程
			*/
			int Start();

			/*
			* 结束工作线程(可重复启动)
			*/
			void Stop();
		private:
			SafeQueue::safe_queue<sWorkItem> m_msg;
			pthread_t tid;
			bool m_bStop;
		};
	}
}

ThreadWorkUnit.cpp

#include "ThreadWorkUnit.h"
#include "AutoLock.h"
#include "../OS/OS.h" //只是一个sleep头文件

namespace Extralib
{
	namespace Thread
	{

		template <typename TYPE, int (TYPE::*svc)() >
		void* _thread_t(void* param)
		{
			TYPE* This = (TYPE*)param;
			This->svc();
			return NULL;
		}

		ThreadWorkUnit::ThreadWorkUnit()
		{
			m_bStop = true;
		}

		ThreadWorkUnit::~ThreadWorkUnit()
		{

		}

		int ThreadWorkUnit::svc()
		{
			return 0;
		}

		void ThreadWorkUnit::PushItem(const sWorkItem& data)
		{
			m_msg.push(data);
		}

		bool ThreadWorkUnit::PopItem(sWorkItem& data)
		{
			return m_msg.try_pop(data);
		}

		void ThreadWorkUnit::PopAllItems(std::list<sWorkItem>& result_queue)
		{
			m_msg.exchange(result_queue);
		}

		int ThreadWorkUnit::Start()
		{
			m_bStop = false;

			pthread_create(&tid, NULL, _thread_t<ThreadWorkUnit, &ThreadWorkUnit::svc>, this);
			return 1;
		}

		void ThreadWorkUnit::Stop()
		{
			m_bStop = true;
		}

		bool ThreadWorkUnit::GetItem( sWorkItem& data )
		{
			if(!m_msg.empty())
			{
				data = m_msg.front();
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}

 

posted @ 2020-12-08 10:45  byfei  阅读(388)  评论(0编辑  收藏  举报