io_service_pool.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #ifndef REST_RPC_IO_SERVICE_POOL_H_
  2. #define REST_RPC_IO_SERVICE_POOL_H_
  3. #include <vector>
  4. #include <memory>
  5. #include "use_asio.hpp"
  6. namespace rest_rpc {
  7. namespace rpc_service {
  8. class io_service_pool : private asio::noncopyable {
  9. public:
  10. explicit io_service_pool(std::size_t pool_size) : next_io_service_(0) {
  11. if (pool_size == 0) throw std::runtime_error("io_service_pool size is 0");
  12. for (std::size_t i = 0; i < pool_size; ++i) {
  13. io_service_ptr io_service(new boost::asio::io_service);
  14. work_ptr work(new boost::asio::io_service::work(*io_service));
  15. io_services_.push_back(io_service);
  16. work_.push_back(work);
  17. }
  18. }
  19. void run() {
  20. std::vector<std::shared_ptr<std::thread>> threads;
  21. for (std::size_t i = 0; i < io_services_.size(); ++i) {
  22. threads.emplace_back(
  23. std::make_shared<std::thread>([](io_service_ptr svr) { svr->run(); }, io_services_[i]));
  24. }
  25. for (std::size_t i = 0; i < threads.size(); ++i) threads[i]->join();
  26. }
  27. void stop() {
  28. for (std::size_t i = 0; i < io_services_.size(); ++i) {
  29. io_services_[i]->stop();
  30. }
  31. }
  32. boost::asio::io_service& get_io_service() {
  33. boost::asio::io_service& io_service = *io_services_[next_io_service_];
  34. ++next_io_service_;
  35. if (next_io_service_ == io_services_.size()) next_io_service_ = 0;
  36. return io_service;
  37. }
  38. private:
  39. typedef std::shared_ptr<boost::asio::io_service> io_service_ptr;
  40. typedef std::shared_ptr<boost::asio::io_service::work> work_ptr;
  41. /// The pool of io_services.
  42. std::vector<io_service_ptr> io_services_;
  43. /// The work that keeps the io_services running.
  44. std::vector<work_ptr> work_;
  45. /// The next io_service to use for a connection.
  46. std::size_t next_io_service_;
  47. };
  48. } // namespace rpc_service
  49. } // namespace rest_rpc
  50. #endif // REST_RPC_IO_SERVICE_POOL_H_