2 // impl/thread_pool.ipp
3 // ~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
11 #ifndef BOOST_ASIO_IMPL_THREAD_POOL_IPP
12 #define BOOST_ASIO_IMPL_THREAD_POOL_IPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
20 #include <boost/asio/thread_pool.hpp>
21 #include <boost/asio/detail/throw_exception.hpp>
23 #include <boost/asio/detail/push_options.hpp>
28 struct thread_pool::thread_function
30 detail::scheduler* scheduler_;
34 #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
37 #endif// !defined(BOOST_ASIO_NO_EXCEPTIONS)
38 boost::system::error_code ec;
40 #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
46 #endif// !defined(BOOST_ASIO_NO_EXCEPTIONS)
50 #if !defined(BOOST_ASIO_NO_TS_EXECUTORS)
53 inline long default_thread_pool_size()
55 std::size_t num_threads = thread::hardware_concurrency() * 2;
56 num_threads = num_threads == 0 ? 2 : num_threads;
57 return static_cast<long>(num_threads);
62 thread_pool::thread_pool()
63 : scheduler_(add_scheduler(new detail::scheduler(*this, 0, false))),
64 num_threads_(detail::default_thread_pool_size())
66 scheduler_.work_started();
68 thread_function f = { &scheduler_ };
69 threads_.create_threads(f, static_cast<std::size_t>(num_threads_));
71 #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS)
75 inline long clamp_thread_pool_size(std::size_t n)
79 std::out_of_range ex("thread pool size");
80 boost::asio::detail::throw_exception(ex);
82 return static_cast<long>(n & 0x7FFFFFFF);
87 thread_pool::thread_pool(std::size_t num_threads)
88 : scheduler_(add_scheduler(new detail::scheduler(
89 *this, num_threads == 1 ? 1 : 0, false))),
90 num_threads_(detail::clamp_thread_pool_size(num_threads))
92 scheduler_.work_started();
94 thread_function f = { &scheduler_ };
95 threads_.create_threads(f, static_cast<std::size_t>(num_threads_));
98 thread_pool::~thread_pool()
104 void thread_pool::stop()
109 void thread_pool::attach()
112 thread_function f = { &scheduler_ };
116 void thread_pool::join()
118 if (!threads_.empty())
120 scheduler_.work_finished();
125 detail::scheduler& thread_pool::add_scheduler(detail::scheduler* s)
127 detail::scoped_ptr<detail::scheduler> scoped_impl(s);
128 boost::asio::add_service<detail::scheduler>(*this, scoped_impl.get());
129 return *scoped_impl.release();
132 void thread_pool::wait()
134 scheduler_.work_finished();
141 #include <boost/asio/detail/pop_options.hpp>
143 #endif // BOOST_ASIO_IMPL_THREAD_POOL_IPP