Files
wnmj/Servers/服务器组件/服务核心/WHAllocationID.cpp

85 lines
1.7 KiB
C++
Raw Normal View History

2026-02-13 14:34:15 +08:00
#include "StdAfx.h"
#include <vector>
#include "WHAllocationID.h"
#include "WHDataLocker.h"
using std::vector;
WHAllocationID::WHAllocationID(int nMaxSize)
{
ReAllocate(nMaxSize);
}
void WHAllocationID::ReAllocate(int nMaxSize)
{
int nSize = m_allocationIDMap.size();
if ( (nSize + 1) >= nMaxSize )
{ // +1<><31><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>ȥ<EFBFBD><C8A5>;
return;
}
CWHDataLocker DataLocker(m_CriticalSection);
m_allocationIDQueue.clear();
m_allocationIDMap.clear();
vector<int > allocationIDVec;
for (int i = 1; i < nMaxSize; ++i)
{
allocationIDVec.push_back(i);
}
int nVecSize = nMaxSize - 1;
int nVecIndex = 0;
int nRandValue = 0;
nSize = 0;
do{
srand((nMaxSize - nSize) * 10 + nSize + time(NULL));
nVecIndex = rand() % nVecSize;
nRandValue = allocationIDVec[nVecIndex];
m_allocationIDQueue.push_back(nRandValue);
m_allocationIDMap.insert(std::make_pair(nRandValue, true));
allocationIDVec.erase(allocationIDVec.begin() + nVecIndex);
nVecSize = allocationIDVec.size();
++nSize;
} while ((nSize + 1) < nMaxSize);
}
int WHAllocationID::PopValue()
{
CWHDataLocker DataLocker(m_CriticalSection);
if (m_allocationIDQueue.empty())
{
return 0;
}
int nRet = m_allocationIDQueue.front();
m_allocationIDQueue.pop_front();
map < int, bool >::iterator iterFind = m_allocationIDMap.find(nRet);
if ( iterFind != m_allocationIDMap.end() )
{ //<2F><><EFBFBD><EFBFBD>ʹ<EFBFBD>ñ<EFBFBD>־;
iterFind->second = false;
}
return nRet;
}
void WHAllocationID::PushValue(int nID)
{
CWHDataLocker DataLocker(m_CriticalSection);
map < int, bool >::iterator iterFind = m_allocationIDMap.find(nID);
if (iterFind == m_allocationIDMap.end())
{ //û<><C3BB><EFBFBD>ҵ<EFBFBD>;
return;
}
if (iterFind->second == true)
{ //<2F><>û<EFBFBD><C3BB>ʹ<EFBFBD><CAB9>;
return;
}
iterFind->second = true;
m_allocationIDQueue.push_back(nID);
}