BOOL CTreadSafeMsgQueue::GetMsg(MsgItem &Msg, int WaitTime)
{
if (!m_bInitedOK) return FALSE;
// 防止在reset期间导致Semaphore计数不正确
while (m_bStop)
{
TRACE("Thread %d Sleep\n", GetCurrentThreadId());
Sleep(SLEEP_TIME);
}
// 进入同步操作状态
m_ReadingThreadNum++;
if (WaitForSingleObject(m_S_Consumer, WaitTime) == WAIT_OBJECT_0)
{
if (WaitForSingleObject(m_E_Queue, WaitTime) == WAIT_OBJECT_0)
{
// OK now, Get message then
Msg = m_Queue[m_TailToRead++];
if (m_TailToRead >= MAX_QUE_SIZE) m_TailToRead = 0;
TRACE("Get message === %d\n", Msg.MsgID);
ReleaseSemaphore(m_S_Producer, 1, NULL);
SetEvent(m_E_Queue);
m_ReadingThreadNum--;
return TRUE;
}
else // wait event time out
{
// not Get message so release Consumer
ReleaseSemaphore(m_S_Consumer, 1, NULL);
SetEvent(m_E_Queue);
m_ReadingThreadNum--;
return FALSE;
}
}
else // wait semaphore time out
{
m_ReadingThreadNum--;
return FALSE;
}
}