建立乙個執行緒池,每有乙個連線物件就將它新增到工作佇列中,執行緒池中的執行緒通過競爭來取得任務並執行它(它是通過訊號量實現的)。
//filename threadpool.h
#ifndef threadpool_h
#define threadpool_h
#include #include #include #include #include template class threadpool;
templatethreadpool::threadpool(int thread_number,int max_requests):m_thread_number(thread_number),
m_max_requests(max_requests),m_stop(false),m_threads(null)
m_threads=new pthread_t[m_thread_number];
if(!m_threads)
//建立執行緒,並將他們都設為分離執行緒,這樣執行緒結束時就能自動釋放資源
for(int i=0;ithreadpool::~threadpool()
m_queuelocker.lock();
if(m_workqueue.size() > m_max_requests)
m_workqueue.push_back(request);
m_queuelocker.unlock();
m_queuestat.post();
return true;
}templatevoid * threadpool::worker(void *arg)
templatevoid threadpool::run()
t* request =m_workqueue.front();
m_workqueue.pop_front();
m_queuelocker.unlock();
if(!request)
request->process();
}}#endif
自己動手寫的Web伺服器《一》
背景介紹 書到用時方恨少,工作之後才知道自己的知識有多麼的困乏,學識有多麼的淺薄。好在我的程式設計師工作不那麼苦逼,每天有大把的時間讓我學我學習,經 程式設計師 的推薦,花大價錢買了一本 深入理解計算機系統 對於這本書,我的評價是 計算機知識的高品質富礦。於是我拿著這本書開始修煉內功,只恨學校沒有使...
自己寫Http伺服器(四)新增執行緒池
在我們伺服器之前的那部分,我們通過建立執行緒讓執行緒去處理任務,從而可以在同一時間可以處理多個請求,但是這樣則需要我們頻繁的建立 銷毀執行緒,這樣在一定程度上會產生資源的損耗,影響我們伺服器的效率,其次如果短時間內的大量請求,導致伺服器建立執行緒數量過多,可能導致記憶體達到極限,影響作業系統中其他重...
基於執行緒池的http伺服器
public static void main string args catch ioexception e 這是整個程式的入口,初始化該初始化的,監聽該 監聽的。threadpoolmanager用於管理執行緒,初始化有三個執行緒。accept方法會造成阻塞,知道有訊息傳過來。將接收到的訊息傳入...