|
| 1 | +#pragma once |
| 2 | +#include <boost/noncopyable.hpp> |
| 3 | +#include <mutex> |
| 4 | +#include <vector> |
| 5 | +#include <assert.h> |
| 6 | +#include <functional> |
| 7 | +#include <iostream> |
| 8 | +#include <thread> |
| 9 | +#include "CallBacks.h" |
| 10 | +#include "Semaphore.h" |
| 11 | +#include "BlockingQueue.h" |
| 12 | + |
| 13 | + |
| 14 | +class ThreadPool : boost::noncopyable |
| 15 | +{ |
| 16 | + class connection_pool; |
| 17 | + typedef std::vector<std::thread*> ThreadPtrVector; |
| 18 | + typedef BlockingQueue<WeakTcpConnectionPtr> messageQueue; |
| 19 | +public: |
| 20 | + ThreadPool(int thread_number = 4, int max_requests = 10000); |
| 21 | + |
| 22 | + //最好不要再初始化里注册回调函数,有可能出问题。 |
| 23 | + void init(); |
| 24 | + void append(WeakTcpConnectionPtr& events); |
| 25 | + void append(WeakTcpConnectionPtr&& events); |
| 26 | + void run(); |
| 27 | + ~ThreadPool(); |
| 28 | + |
| 29 | +private: |
| 30 | + bool stop; |
| 31 | + //std::mutex mutexLock; |
| 32 | + ThreadPtrVector thread_pool; |
| 33 | + messageQueue workQue; |
| 34 | + //connection_pool* conn_pool; |
| 35 | + //Semaphore queuestate; |
| 36 | +}; |
| 37 | + |
| 38 | + |
| 39 | +inline ThreadPool::ThreadPool(int thread_number, int max_requests): |
| 40 | + thread_pool(thread_number), stop(false), workQue(max_requests) |
| 41 | +{ |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +inline void ThreadPool::init() |
| 46 | +{ |
| 47 | + for (int i = 0; i < thread_pool.size(); ++i) { |
| 48 | + thread_pool[i] = new std::thread(std::bind(&ThreadPool::run, this)); |
| 49 | + assert(thread_pool[i] != nullptr); |
| 50 | + thread_pool[i]->detach(); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +inline void ThreadPool::append(WeakTcpConnectionPtr& events) |
| 56 | +{ |
| 57 | + workQue.append(events); |
| 58 | +} |
| 59 | + |
| 60 | +inline void ThreadPool::append(WeakTcpConnectionPtr&& events) |
| 61 | +{ |
| 62 | + workQue.append(std::move(events)); |
| 63 | +} |
| 64 | + |
| 65 | +inline void ThreadPool::run() |
| 66 | +{ |
| 67 | + while (!stop) |
| 68 | + { |
| 69 | + auto req(std::move(workQue.take())); |
| 70 | + auto ptr = req.lock(); |
| 71 | + if(ptr != nullptr) ptr->handleEvents(); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | + |
| 76 | +inline ThreadPool::~ThreadPool() |
| 77 | +{ |
| 78 | + //如何安全退出? |
| 79 | + stop = true; |
| 80 | + for (int i = 0; i < thread_pool.size(); ++i) delete thread_pool[i]; |
| 81 | +} |
| 82 | + |
0 commit comments