// 工程名称:网络游戏服务器端引擎《hryEngine》
// 参考项目:ReactOS、Apache、ACE、
// Created by Liao Huaifu,Shanghai,2009/9/20,QQ:279670696
【路过的朋友请留下您宝贵的意见,谢谢!】
#pragma once #include <Windows.h> /*************************************************************************************** 文件名:MsgQueue.h 类名: MsgQueue 描述: 本模板实现了固定大小Node的消息队列,其中通过循环队列实现了O(1)时间复杂度EnQueue与DeQueue操作, 同时采用内存池式内存管理,整个生命周期消耗内存大小不变,不产生任何内存碎片。 说明: 读者可以根据自己的需要添加“自动锁”来确保多线程操作安全 ***************************************************************************************/ namespace LHF_MSG_QUEUE { enum { MSG_DEFAULT_MAX = 2048, };
template <class T> class MsgQueue { public: MsgQueue(DWORD dwMsgMax = 0); ~MsgQueue();
void EnQueue(const T &msg); //将msg加入到队列中
T DeQueue(); //删除并返回队头元素
BOOL IsEmpty() {return m_dwMessageQueueCount == 0;} private: CLock m_lock; T* m_pMsgQue; DWORD m_dwMessageQueueHead; // 队头
DWORD m_dwMessageQueueTail; // 队尾
DWORD m_dwMessageQueueCount; // 当前消息数
DWORD m_dwMessageQueueMax; // 最大消息数
};
template <class T> MsgQueue<T>::MsgQueue(DWORD dwMsgMax) { m_dwMessageQueueHead = 0; m_dwMessageQueueTail = 0; m_dwMessageQueueCount = 0; m_pMsgQue = NULL;
if (!dwMsgMax) { m_dwMessageQueueMax = MSG_DEFAULT_MAX; } else { m_dwMessageQueueMax = dwMsgMax; }
m_pMsgQue = new T[m_dwMessageQueueMax]; memset(m_pMsgQue,0,sizeof(T)*m_dwMessageQueueMax); }
template <class T> MsgQueue<T>::~MsgQueue() { if (m_pMsgQue) { delete[] m_pMsgQue; m_pMsgQue = NULL; } }
template <class T> void MsgQueue<T>::EnQueue(const T &msg) { if (m_dwMessageQueueCount == m_dwMessageQueueMax) { printf("MsqQue is full.\n"); return; }
m_pMsgQue[m_dwMessageQueueTail] = msg; m_dwMessageQueueTail = (m_dwMessageQueueTail+1) % m_dwMessageQueueMax; m_dwMessageQueueCount++; }
template <class T> T MsgQueue<T>::DeQueue() { T tmpData; if (!m_dwMessageQueueCount) { printf("MsqQue is empty.\n"); } else { tmpData = m_pMsgQue[m_dwMessageQueueHead]; m_dwMessageQueueHead = (m_dwMessageQueueHead+1) % m_dwMessageQueueMax; m_dwMessageQueueCount--; } return tmpData; } }
|
阅读(855) | 评论(0) | 转发(0) |