四、連接池的實(shí)現(xiàn)
每個(gè)連接池保存一個(gè)鏈表保存已經(jīng)建立的連接:list<MyConnection *> * m_connections
當(dāng)然這個(gè)鏈表也需要鎖來進(jìn)行多線程保護(hù):pthread_mutex_t m_connectionMutex;
此處一個(gè)MyConnection也是一個(gè)MyTask,由一個(gè)線程來負(fù)責(zé)。
線程池也作為連接池的成員變量:MyThreadPool * m_threadPool
連接池由類MyConnectionPool負(fù)責(zé),其主要函數(shù)如下:
void MyConnectionPool::addConnection(MyConnection * pConn)
{
pthread_mutex_lock(&m_connectionMutex);
m_connections->push_back(pConn);
pthread_mutex_unlock(&m_connectionMutex);
m_threadPool->addTask(pConn);
}
MyConnectionPool也要啟動(dòng)一個(gè)背后的線程,來管理這些連接,移除結(jié)束的連接和錯(cuò)誤的連接。
void MyConnectionPool::managePool()
{
pthread_mutex_lock(&m_connectionMutex);
for (list<MyConnection *>::iterator itr = m_connections->begin(); itr!=m_connections->end(); )
{
MyConnection *conn = *itr;
if (conn->isFinish())
{
delete conn;
conn = NULL;
list<MyConnection *>::iterator pos = itr++;
m_connections->erase(pos);
}
else if (conn->isError())
{
//處理錯(cuò)誤的連接
++itr;
}
else
{
++itr;
}
}
pthread_mutex_unlock(&m_connectionMutex);
}
本文導(dǎo)航
- 第1頁: 首頁
- 第2頁: 對(duì)Socket的封裝
- 第3頁: 線程池的實(shí)現(xiàn)
- 第4頁: 連接池的實(shí)現(xiàn)
- 第5頁: 監(jiān)聽線程的實(shí)現(xiàn)