thread_pool.ipp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // impl/thread_pool.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 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_(use_service<detail::scheduler>(*this))
  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_(use_service<detail::scheduler>(*this))
  39. {
  40. scheduler_.work_started();
  41. thread_function f = { &scheduler_ };
  42. threads_.create_threads(f, num_threads);
  43. }
  44. thread_pool::~thread_pool()
  45. {
  46. stop();
  47. join();
  48. }
  49. void thread_pool::stop()
  50. {
  51. scheduler_.stop();
  52. }
  53. void thread_pool::join()
  54. {
  55. scheduler_.work_finished();
  56. threads_.join();
  57. }
  58. } // namespace asio
  59. } // namespace boost
  60. #include <boost/asio/detail/pop_options.hpp>
  61. #endif // BOOST_ASIO_IMPL_THREAD_POOL_IPP