thread_pool.ipp 1.9 KB

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