100分请高人指点,为什么我的多线程队列会出错!
我自己写了一个多线程用的队列模版,在插入和取出的速度相同的情况下不出错,可是在取出速度大于插入速度的时候,就会报Debug Assertion Failed错误,我已经知道是因为取了空值的缘故!可是我就是不知道的我的模版错在那儿了!请高人指点!下面是我的多线程模版类:
template<class Type>
class CQueue
{
private:
CList<Type,Type&>m_List;
CRITICAL_SECTION m_lock;
HANDLE m_hOutEvent;
HANDLE m_hInEvent;
int m_nMax;
BOOL m_bDrop;
public:
//初始化队列
CQueue(int nQueueLength=10,BOOL bDrop=FALSE)
{
m_nMax=nQueueLength;
m_bDrop=bDrop;
InitializeCriticalSection(&m_lock);
m_hInEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
assert(m_hInEvent!=NULL);
m_hOutEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
assert(m_hOutEvent!=NULL);
}
//销毁队列
~CQueue()
{
DeleteCriticalSection(&m_lock);
CloseHandle(m_hInEvent);
CloseHandle(m_hOutEvent);
m_List.RemoveAll();
}
//插入元素item到队尾
void EnQueue(Type item)
{
EnterCriticalSection(&m_lock);
if (m_List.GetCount()>=m_nMax)
{
ResetEvent(m_hInEvent);
LeaveCriticalSection(&m_lock);
if (m_bDrop) return;
if (WaitForSingleObject(m_hInEvent,INFINITE)!= WAIT_OBJECT_0)
assert(FALSE);
EnterCriticalSection(&m_lock);
}
m_List.AddTail(item);
SetEvent(m_hOutEvent);
LeaveCriticalSection(&m_lock);
}
//删除队列的队头元素,并返回元素
Type DeQueue()
{
Type type;
EnterCriticalSection(&m_lock);
// 如果队列为空
if (m_List.IsEmpty())
{
ResetEvent(m_hOutEvent);
LeaveCriticalSection(&m_lock);
if (WaitForSingleObject(m_hOutEvent, INFINITE) != WAIT_OBJECT_0)
ASSERT(FALSE);
EnterCriticalSection(&m_lock);
}
type = m_List.RemoveHead();
SetEvent(m_hInEvent);
LeaveCriticalSection(&m_lock);
return type;
}
//取得队列头部元素
Type GetHead()
{
Type head;
EnterCriticalSection(&m_lock);
head=m_List.GetHead();
LeaveCriticalSection(&m_lock);
return head;
}
//返回队列长度
int GetLength()
{
int nCount = 0;
EnterCriticalSection(&m_lock);
nCount = m_List.GetCount();
LeaveCriticalSection(&m_lock);
return nCount;
}
//清空队列
void ClearQueue()
{
EnterCriticalSection(&m_lock);
m_List.RemoveAll();
LeaveCriticalSection(&m_lock);
}
//检测队列是否为空,为空返回TRUE,不空返回FALSE;
BOOL IsEmpty()
{
BOOL bEmpty;
EnterCriticalSection(&m_lock);
bEmpty=m_List.IsEmpty();
LeaveCriticalSection(&m_lock);
return bEmpty;
}
//检测队列是否为满
BOOL IsFull()
{
BOOL bFull;
EnterCriticalSection(&m_lock);
bFull=(m_List.GetCount()>=m_nMax);
LeaveCriticalSection(&m_lock);
return bFull;
}
};