ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ### boost实现线程池 ***** #### 一个io_service 多个线程 ``` using namespace std; using namespace boost; typedef std::shared_ptr<std::thread> thread_ptr; typedef std::vector<thread_ptr> vecThread; class ThreadPool { public: ThreadPool(int num) : threadNum_(num), stopped_(false), work_(io_) { for(int i=i; i<threadNum_; ++i) { threads_.push_back(std::make_shared<std::thread>([&](){io_.run();})); } } ~ThreadPool() { stop(); } template<typename F, typename...Args> void post(F &&f, Args&&...args) { io_.post(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); } void stop() { if(!stopped_) { io_.stop(); for(auto t : threads_) t->join(); stopped_ = true; } } private: bool stopped_; vecThread threads_; int threadNum_; asio::io_service io_; asio::io_service::work work_; }; ``` #### 多个io_serviced多个线程 ``` class AsioIOServicePool { public: using IOService = boost::asio::io_service; using Work = boost::asio::io_service::work; using WorkPtr = std::unique_ptr<Work>; AsioIOServicePool(std::size_t size = std::thread::hardware_concurrency()) : ioServices_(size), works_(size), nextIOService_(0) { for (std::size_t i = 0; i < size; ++i) { works_[i] = std::unique_ptr<Work>(new Work(ioServices_[i])); } for (std::size_t i = 0; i < ioServices_.size(); ++i) { threads_.emplace_back([this, i] () { ioServices_[i].run(); }); } } AsioIOServicePool(const AsioIOServicePool &) = delete; AsioIOServicePool &operator=(const AsioIOServicePool &) = delete; // 使用 round-robin 的方式返回一个 io_service boost::asio::io_service &getIOService() { auto &service = ioServices_[nextIOService_++]; if (nextIOService_ == ioServices_.size()) { nextIOService_ = 0; } return service; } void stop() { for (auto &work: works_) { work.reset(); } for (auto &t: threads_) { t.join(); } } private: std::vector<IOService> ioServices_; std::vector<WorkPtr> works_; std::vector<std::thread> threads_; std::size_t nextIOService_; }; ```