1// 2// impl/thread_pool.ipp 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#ifndef BOOST_ASIO_IMPL_THREAD_POOL_IPP 12#define BOOST_ASIO_IMPL_THREAD_POOL_IPP 13 14#if defined(_MSC_VER) && (_MSC_VER >= 1200) 15# pragma once 16#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) 17 18#include <boost/asio/detail/config.hpp> 19#include <boost/asio/thread_pool.hpp> 20 21#include <boost/asio/detail/push_options.hpp> 22 23namespace boost { 24namespace asio { 25 26struct thread_pool::thread_function 27{ 28 detail::scheduler* scheduler_; 29 30 void operator()() 31 { 32 boost::system::error_code ec; 33 scheduler_->run(ec); 34 } 35}; 36 37thread_pool::thread_pool() 38 : scheduler_(add_scheduler(new detail::scheduler(*this, 0, false))) 39{ 40 scheduler_.work_started(); 41 42 thread_function f = { &scheduler_ }; 43 std::size_t num_threads = detail::thread::hardware_concurrency() * 2; 44 threads_.create_threads(f, num_threads ? num_threads : 2); 45} 46 47thread_pool::thread_pool(std::size_t num_threads) 48 : scheduler_(add_scheduler(new detail::scheduler( 49 *this, num_threads == 1 ? 1 : 0, false))) 50{ 51 scheduler_.work_started(); 52 53 thread_function f = { &scheduler_ }; 54 threads_.create_threads(f, num_threads); 55} 56 57thread_pool::~thread_pool() 58{ 59 stop(); 60 join(); 61} 62 63void thread_pool::stop() 64{ 65 scheduler_.stop(); 66} 67 68void thread_pool::join() 69{ 70 if (!threads_.empty()) 71 { 72 scheduler_.work_finished(); 73 threads_.join(); 74 } 75} 76 77detail::scheduler& thread_pool::add_scheduler(detail::scheduler* s) 78{ 79 detail::scoped_ptr<detail::scheduler> scoped_impl(s); 80 boost::asio::add_service<detail::scheduler>(*this, scoped_impl.get()); 81 return *scoped_impl.release(); 82} 83 84} // namespace asio 85} // namespace boost 86 87#include <boost/asio/detail/pop_options.hpp> 88 89#endif // BOOST_ASIO_IMPL_THREAD_POOL_IPP 90