项目github https://github.com/dreamyouxi/LiteHttp
文件ThreadPool.cpp
1#include "ThreadPool.h" 2#include "winsock.h" 3#include "stdlib.h" 4#include "stdio.h" 5#include "string.h" 6#include <fstream> 7#include <iostream> 8#include <string> 9#include <atomic> 10#include "Defs.h" 11#include "FileCache.h" 12#include "HttpRequest.h" 13#include "HttpRespone.h" 14 15using namespace std; 16 17 18void SendThread(HttpRespone* rep) 19{ 20 send(rep->sock, (const char*)rep->header, rep->header_size, 0); 21 send(rep->sock, (const char*)rep->buffer,rep->size, 0); 22 23} 24 25class ThreadCounterRAII 26{ 27public: 28 ThreadCounterRAII() 29 { 30 _count.fetch_add(1); 31 } 32 33 static atomic<int > _count; 34 ~ThreadCounterRAII() 35 { 36 _count.fetch_sub(1); 37 } 38 39}; 40 41atomic<int> ThreadCounterRAII::_count = 0; 42 43void ProcessRequestThread(HttpRequest*request ) 44{ 45 ThreadCounterRAII counter; 46 .......... 47} 48 49 50ThreadPool * ThreadPool::getInstance() 51{ 52 static ThreadPool * ins = nullptr; 53 if (!ins)ins = new ThreadPool; 54 return ins; 55} 56 57 58 59void ThreadPool::WorkThread() 60{ 61 while (true) 62 { 63 this->_mutex.lock(); 64 while(this->works.empty()) 65 { 66 this->_cond.wait(this->_mutex); 67 } 68 HttpRequest * req = this->works.front(); 69 this->works.pop(); 70 this->_mutex.unlock(); 71 ProcessRequestThread(req); 72 } 73} 74 75 76void ThreadPool::addTask(HttpRequest*work) 77{ 78 this->_mutex.lock(); 79 this->works.push(work); 80 this->_mutex.unlock(); 81 82 this->_cond.notify_one(); 83} 84 85ThreadPool::ThreadPool() 86{ 87 int MAX_THREADS = std::thread::hardware_concurrency(); 88 89 while (MAX_THREADS--) 90 { 91 std::thread t(std::bind(&ThreadPool::WorkThread, this)); 92 93 t.detach(); 94 this->workers.push_back(std::move(t)); 95 } 96}
程序初始化时启动 10个工作线程,主线程接收到的TCP链接请求全部加入请求队列,工作线程处理
主线程:Application.cpp
1 while (true) 2 { 3 int sock_client = accept(sock, (sockaddr *)&client_ipaddr, &length); 4 if (sock_client == SOCKET_ERROR) 5 { 6 return; 7 } 8 HttpRequest*req = new HttpRequest; 9 req->sock = sock_client; 10 ThreadPool::getInstance()->addTask(req); 11 }