一 、又是看到老大使用的技能,二话不说先mark下来,直接上代码
#include <functional>
#include <boost/asio.hpp>
#include <thread>
namespace wayos {
class ThreadPool {
// 线程池中需要执行的方法类型。
typedef std::function<void()> VoidHandler;
public:
// 用全局静态变量,不属于具体的对象
static ThreadPool& getInstance() {
static ThreadPool threadPool;
return threadPool;
}
boost::asio::io_service& getIoService() {
return mIoService;
}
// 把要执行的方法扔到线程池中
void post(VoidHandler handler) {
mIoService.post(handler);
}
private:
// 线程池最大线程数
static constexpr int THREAD_NUM = 10;
boost::asio::io_service mIoService;
std::thread *mThreads[THREAD_NUM];
// 将mIoService扔给work,目的就是即使没有 handler进来,run执行结束之后,也不会导致线程池中的线程退出
boost::asio::io_service::work mWork;
ThreadPool()
:mIoService(),mWork(mIoService)
{
for(int i = 0; i < THREAD_NUM; ++i)
{
// 产生十个线程
mThreads[i] = new std::thread([this]{ mIoService.run();});
}
}
};
}