template <typename TYPE>
class CHMQ
{
public:
CHMQ()
{
m_nMax = -1;
m_bDrop = FALSE;
::InitializeCriticalSection(&m_lock);
m_hPushEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
//ASSERT(m_hPushEvent != NULL);
m_hPopEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
//ASSERT(m_hPopEvent != NULL);
}
~CHMQ()
{
::DeleteCriticalSection(&m_lock);
::CloseHandle(m_hPushEvent);
::CloseHandle(m_hPopEvent);
//m_list.RemoveAll();
}
// 隊列尾增加消息,如果消息隊列已滿,根據設定或丟棄消息,或阻塞直到隊列不爲滿的時候。
void Push(TYPE& type)
{
::EnterCriticalSection(&m_lock);
// 如果消息隊列已滿
//if ( m_nMax > 0 && m_list.GetCount() >= m_nMax)
if ( m_nMax > 0 && m_queue.size() >= m_nMax)
{
::ResetEvent(m_hPushEvent);
::LeaveCriticalSection(&m_lock);
if( m_bDrop )
return;
if ( ::WaitForSingleObject(m_hPushEvent, INFINITE) != WAIT_OBJECT_0)
//ASSERT(FALSE);
;
::EnterCriticalSection(&m_lock);
}
//m_list.AddTail(type);
m_queue.push(type);
::SetEvent(m_hPopEvent);
::LeaveCriticalSection(&m_lock);
}
//// 隊列頭增加消息,如果消息隊列已滿,根據設定或丟棄消息,或阻塞直到隊列不爲滿的時候。
//void Insert(TYPE& type)
//{
// ::EnterCriticalSection(&m_lock);
// // 如果消息隊列已滿
// //if ( m_nMax > 0 && m_list.GetCount() >= m_nMax)
// if ( m_nMax > 0 && m_queue.size() >= m_nMax)
// {
// ::ResetEvent(m_hPushEvent);
// ::LeaveCriticalSection(&m_lock);
// if( m_bDrop )
// return;
// if ( ::WaitForSingleObject(m_hPushEvent, INFINITE) != WAIT_OBJECT_0)
// ASSERT(FALSE);
// ::EnterCriticalSection(&m_lock);
// }
// m_list.AddHead(type);
// ::SetEvent(m_hPopEvent);
// ::LeaveCriticalSection(&m_lock);
//}
// 從隊列頭中取消息,如果隊列爲空則阻塞,直到不爲空的時候。
TYPE Pop()
{
TYPE type;
DWORD id = GetCurrentThreadId();
::EnterCriticalSection(&m_lock);
// 如果隊列爲空
//if (m_list.IsEmpty())
if (m_queue.size() == 0)
{
::ResetEvent(m_hPopEvent);
::LeaveCriticalSection(&m_lock);
if ( ::WaitForSingleObject(m_hPopEvent, INFINITE) != WAIT_OBJECT_0)
//ASSERT(FALSE);
;
::EnterCriticalSection(&m_lock);
}
//type = m_list.RemoveHead();
type = m_queue.front();
m_queue.pop();
::SetEvent(m_hPushEvent);
::LeaveCriticalSection(&m_lock);
return type;
}
// 返回目前消息隊列中的消息個數。
int GetQueueCount()
{
int nCount = 0;
::EnterCriticalSection(&m_lock);
//nCount = m_list.GetCount();
nCount = m_queue.size();
::LeaveCriticalSection(&m_lock);
return nCount;
}
// 設置消息隊列的最大長度,以及如果消息隊列滿的時候新消息的處理方式。
//或丟棄消息,或阻塞直到隊列不爲滿的時候。
void SetMaxCount(int nMax = -1, BOOL bDrop = FALSE)
{
::EnterCriticalSection(&m_lock);
m_nMax = nMax;
m_bDrop = bDrop;
::LeaveCriticalSection(&m_lock);
}
// 返回消息隊列的最大長度,如果沒有設置最大長度則返回-1。
int GetMaxCount()
{
::EnterCriticalSection(&m_lock);
::LeaveCriticalSection(&m_lock);
return m_nMax;
}
private:
CRITICAL_SECTION m_lock;
//CList m_list;
queue<TYPE> m_queue;
HANDLE m_hPopEvent;
HANDLE m_hPushEvent;
int m_nMax;
BOOL m_bDrop;
};
multithreadqueue
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.