一个简单的片段
CThreadPool::CThreadPool()
{
int i;
for(i=0;i<MAX_USER_CONNECTION;i++)
{
m_pThreads[i]=new CCommandThread;
m_pThreads[i]->m_nID=i;
m_pThreads[i]->m_pPool=this;
}
m_pDataThreadPool=NULL;
}
CThreadPool::~CThreadPool()
{
int i;
for(i=0;i<MAX_USER_CONNECTION;i++)
{
m_pThreads[i]->PostThreadMessage(WM_QUIT,NULL,NULL);
m_pThreads[i]->ResumeThread();
m_pThreads[i]=NULL;
}
if(m_pDataThreadPool!=NULL)
delete m_pDataThreadPool;
m_pDataThreadPool=NULL;
}
BEGIN_MESSAGE_MAP(CThreadPool, CWnd)
//{{AFX_MSG_MAP(CThreadPool)
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CThreadPool message handlers
//创建线程并暂停
void CThreadPool::CreateThreads()
{
int i;
for(i=0;i<MAX_USER_CONNECTION;i++)
{
m_pThreads[i]->CreateThread(CREATE_SUSPENDED);
}
}
void CThreadPool::Accept(SOCKET hSocket)
{
CCommandThread *pThread;
CCommandSocket tSocket;
CString IP,Str;
UINT Port;
//得到当前可用的线程
pThread=GetFreeThread();
if(pThread==NULL)
{
tSocket.Attach(hSocket);
tSocket.GetPeerName(IP,Port);
Str.Format("因连接过多,来自\"%s:%d\"的连接被拒绝。",IP,Port);
SysLog.AddLogItem(Str,LT_SYSTEM);
tSocket.SendData(MSG_CONNECTBUSY);
tSocket.Close();
return;
}
tSocket.Attach(hSocket);
tSocket.GetPeerName(IP,Port);
Str.Format("\"%s:%d\"连接到本机。",IP,Port);
SysLog.AddLogItem(Str,LT_USER);
tSocket.Detach();
pThread->m_hSocket=hSocket;
pThread->PostThreadMessage(UM_COMMAND,UM_START_WORK,NULL);
pThread->ResumeThread();
}
//得到当前空闲的线程
CCommandThread* CThreadPool::GetFreeThread()
{
int i;
for(i=0;i<MAX_USER_CONNECTION;i++)
{
if(m_pThreads[i]->m_OnUsing==false)
{
m_pThreads[i]->m_OnUsing=true;
//此处要清理m_pThreads[i]的消息队列,不会做
return m_pThreads[i];
}
}
return NULL;
}