1 // 2 // io_context_pool.cpp 3 // ~~~~~~~~~~~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) 6 // 7 // Distributed under the Boost Software License, Version 1.0. (See accompanying 8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 9 // 10 11 #include "server.hpp" 12 #include <stdexcept> 13 #include <boost/thread/thread.hpp> 14 #include <boost/bind.hpp> 15 #include <boost/shared_ptr.hpp> 16 17 namespace http { 18 namespace server2 { 19 io_context_pool(std::size_t pool_size)20io_context_pool::io_context_pool(std::size_t pool_size) 21 : next_io_context_(0) 22 { 23 if (pool_size == 0) 24 throw std::runtime_error("io_context_pool size is 0"); 25 26 // Give all the io_contexts work to do so that their run() functions will not 27 // exit until they are explicitly stopped. 28 for (std::size_t i = 0; i < pool_size; ++i) 29 { 30 io_context_ptr io_context(new boost::asio::io_context); 31 io_contexts_.push_back(io_context); 32 work_.push_back(boost::asio::make_work_guard(*io_context)); 33 } 34 } 35 run()36void io_context_pool::run() 37 { 38 // Create a pool of threads to run all of the io_contexts. 39 std::vector<boost::shared_ptr<boost::thread> > threads; 40 for (std::size_t i = 0; i < io_contexts_.size(); ++i) 41 { 42 boost::shared_ptr<boost::thread> thread(new boost::thread( 43 boost::bind(&boost::asio::io_context::run, io_contexts_[i]))); 44 threads.push_back(thread); 45 } 46 47 // Wait for all threads in the pool to exit. 48 for (std::size_t i = 0; i < threads.size(); ++i) 49 threads[i]->join(); 50 } 51 stop()52void io_context_pool::stop() 53 { 54 // Explicitly stop all io_contexts. 55 for (std::size_t i = 0; i < io_contexts_.size(); ++i) 56 io_contexts_[i]->stop(); 57 } 58 get_io_context()59boost::asio::io_context& io_context_pool::get_io_context() 60 { 61 // Use a round-robin scheme to choose the next io_context to use. 62 boost::asio::io_context& io_context = *io_contexts_[next_io_context_]; 63 ++next_io_context_; 64 if (next_io_context_ == io_contexts_.size()) 65 next_io_context_ = 0; 66 return io_context; 67 } 68 69 } // namespace server2 70 } // namespace http 71