2010-4
程序出现了问题,引出了数据逻辑问题。
下面两个函数GetNextDataIndexW();和SetNextDataIndexW分别锁定,
导致了可能两个线程通过了GetNextDataIndexW();但是在SetNextDataIndexW出现数据写入错误。
这是一个典型的数据同步错误,也是一个涉及到函数封装颗粒度的问题。
BOOL CShareMem::IncreaseNextDataIndex()
{if(m_nExitSignal != 0)return FALSE;int iNextDataW = GetNextDataIndexW();if( iNextDataW < 1) return FALSE;if (iNextDataW >= m_cDataCount-1){iNextDataW = 1;}else{iNextDataW++;}ATLASSERT(iNextDataW < GetDataCount());//SetNextDataIndexW(iNextDataW);return TRUE;
}BOOL CShareMem::DecreaseNextDataIndex()//
{if (m_nExitSignal != 0)return FALSE;int iNextDataW = GetNextDataIndexW();if( iNextDataW < 1) return FALSE;if (iNextDataW <= 1){iNextDataW = m_cDataCount-1;}else{iNextDataW--;}ATLASSERT(iNextDataW>=1);SetNextDataIndexW(iNextDataW);return TRUE;
}
修改为
BOOL CShareMem::IncreaseNextDataIndex()
{ATLASSERT (0 < m_cDataSize && 0 < m_cDataCount);if (0 >= m_cDataCount || 0 >= m_cDataSize)//{CUtil::Instance()->DbgFilePrintf(L"Client",_T("CShareMem::IncreaseNextDataIndex datasize incorrect!!!"));return FALSE;}if(m_nExitSignal != 0)return FALSE;if(!Lock()) return FALSE;int iNextDataW = 0;try{if (m_nExitSignal != 0){Unlock();return FALSE;}ATLASSERT(m_lpvData != NULL);if (m_lpvData != NULL){iNextDataW = *((LONG*)m_lpvData);ATLASSERT(iNextDataW >= 1 && iNextDataW < GetDataCount());if(iNextDataW < 1 || iNextDataW >= GetDataCount())iNextDataW = 0;if (iNextDataW >= m_cDataCount-1){iNextDataW = 1;}else{iNextDataW++;}ATLASSERT(iNextDataW < GetDataCount());//memcpy((LONG*)m_lpvData,(LONG*)(&iNextDataW),sizeof(LONG));}}catch(...){CUtil::Instance()->DbgFilePrintf(L"Client",L"CShareMem::IncreaseNextDataIndex() encounter a error.");}Unlock();return TRUE;
}BOOL CShareMem::DecreaseNextDataIndex()//
{ATLASSERT (0 < m_cDataSize && 0 < m_cDataCount);if (0 >= m_cDataCount || 0 >= m_cDataSize)//{CUtil::Instance()->DbgFilePrintf(L"Client",_T("CShareMem::IncreaseNextDataIndex datasize incorrect!!!"));return FALSE;}if(m_nExitSignal != 0)return FALSE;if(!Lock()) return FALSE;int iNextDataW = 0;try{if (m_nExitSignal != 0){Unlock();return FALSE;}ATLASSERT(m_lpvData != NULL);if (m_lpvData != NULL){iNextDataW = *((LONG*)m_lpvData);ATLASSERT(iNextDataW >= 1 && iNextDataW < GetDataCount());if(iNextDataW < 1 || iNextDataW >= GetDataCount())iNextDataW = 0;if (iNextDataW <= 1){iNextDataW = m_cDataCount-1;}else{iNextDataW--;}ATLASSERT(iNextDataW>=1 && iNextDataW < GetDataCount());//memcpy((LONG*)m_lpvData,(LONG*)(&iNextDataW),sizeof(LONG));}}catch(...){CUtil::Instance()->DbgFilePrintf(L"Client",L"CShareMem::DecreaseNextDataIndex() encounter a error.");}Unlock();return TRUE;
}