1 // 2 // io_context_pool.cpp 3 // ~~~~~~~~~~~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2021 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/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::require(io_context->get_executor(), 33 boost::asio::execution::outstanding_work.tracked)); 34 } 35 } 36 run()37void io_context_pool::run() 38 { 39 // Create a pool of threads to run all of the io_contexts. 40 std::vector<boost::shared_ptr<boost::thread> > threads; 41 for (std::size_t i = 0; i < io_contexts_.size(); ++i) 42 { 43 boost::shared_ptr<boost::thread> thread(new boost::thread( 44 boost::bind(&boost::asio::io_context::run, io_contexts_[i]))); 45 threads.push_back(thread); 46 } 47 48 // Wait for all threads in the pool to exit. 49 for (std::size_t i = 0; i < threads.size(); ++i) 50 threads[i]->join(); 51 } 52 stop()53void io_context_pool::stop() 54 { 55 // Explicitly stop all io_contexts. 56 for (std::size_t i = 0; i < io_contexts_.size(); ++i) 57 io_contexts_[i]->stop(); 58 } 59 get_io_context()60boost::asio::io_context& io_context_pool::get_io_context() 61 { 62 // Use a round-robin scheme to choose the next io_context to use. 63 boost::asio::io_context& io_context = *io_contexts_[next_io_context_]; 64 ++next_io_context_; 65 if (next_io_context_ == io_contexts_.size()) 66 next_io_context_ = 0; 67 return io_context; 68 } 69 70 } // namespace server2 71 } // namespace http 72